Question

I try to copy a command from history. How can I copy the 510th command? Please, see the data below. My bet is:

history | grep 510 | sed '1q;d' | awk '{print $2-$10}' | pbcopy

but the output is 0. I cannot understand the reason. What is wrong in the command?

  505  find . -perm=750 -print0 | xargs -0 chmod 750
  506  find . --perm=750 -print0 | xargs -0 chmod 750
  507  find . -perm=750 -print0 | xargs -0 chmod 750
  508  find . -perm=750 -print0 | xargs -0 chmod 750
  510  find . -perm 750 -print0 | xargs -0 chmod 750
  512  history | grep perm 750 -print0 | pbcopy
Was it helpful?

Solution

If you're using bash:

echo "!510" | pbcopy

(See also "history expansion" in the bash manual)

OTHER TIPS

You can use perl to print everything but the first column (510) of the requested line:

history | perl -ane 'print "@F[1..$#F]" if($F[0]==510)'

For a range of fields in Awk, you need a for-loop. What you're doing is subtraction, thus the result of zero.

Usually the cut command does the task of extracting columns, but sometimes Awk is more appropriate.

Here's what you meant.

history | grep 510 | sed 1q \
 | awk '{for(i = 2; i <= NF; i++){ORS = (i == NF ? "\n" : " "); print $i;}}' \
 | pbcopy

The reason is that $2 and $10 are not numbers in the awk scripts. The fields' indexes are 1-based, so if you want the 750, the first one is $5, the second one is $11.

Note that this is different with the lines with "-perm=750"

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top