awk trick 1: reverse words

Suppose a string “cp -r Documents stam”, want to reverse it to “stam Documents -r cp”. A very simple awk code:

echo “cp -r Documents stam” | awk ‘{ for (i=NF; i>0; i–) printf(“%s “,$i)}’

stam Documents -r cp

NOTE: when copy the above command and run it at command line, quotation marks need to be edited.

Keywords NB and NF are built-in variables, means the beginning number and the total number of fields in current record, respectively. NR is the total number of records read in an input file.

WOW, I didn’t realize how simple it is! I can’t claim that I have used Linux for 10 years any more! 🙁

Comments are closed.