tags:

views:

115

answers:

4

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
+1  A: 

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)'
A: 

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"

jpalecek
I think the person wants a range of fields, and not subtraction. Stunning coincidence, though!
ashawley
+6  A: 

If you're using bash:

echo "!510" | pbcopy

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

sth
It worked me without quotes as well. Thank you!
Masi
@UnixBasics: Don't try to use that without quotes, it will hurt you.
Juliano
+1  A: 

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
ashawley