Reversing the Words on Each Line
problem
You want to print the input lines with words in the reverse order.
Solution
$ awk '{
> for (i=NF; i>0; i--) {
> printf "%s ", $i;
> }
> printf "\n"
> }'You don’t type the > characters; the shell will print those as a prompt to say that you haven’t ended your command yet (it is looking for the matching single-quote mark). Because the awk program is enclosed in single quotes, the bash shell lets us type multiple lines, prompting us with the secondary prompt > until we supply the matching end quote. We spaced out the program for readability, even though we could have stuffed it all onto one line like this:
$ awk '{for (i=NF; i>0; i--) {printf "%s ", $i;} printf "\n" }'Discussion
The awk program has syntax for a for loop, very much
in the C language style. It even
supports a printf mechanism for
formatted output, again modeled after the C language version (or the
bash version, too). We use the for loop to count down from the last to the
first field, and print each field as we go. We deliberately don’t put a
\n on that first printf because we want to keep the several
fields on the same line of output. When the loop is done, we add a
newline to terminate the line of output.
The reference to $i is very different
in awk compared to bash. In
bash, when we write $i we are getting at the value stored in the
variable named i. But in
awk, as with most programming languages, we simply
reference the value in i by naming
it—that is by just writing i. So what ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access