Skip to content
Advertisement

Linux – flip last bottom lines only, with awk

We are currently learning some awk commands to manipulate/rearrange text on files.

our original text goes like this..1998

JavaScript

It’s asking us to rearrange the columns (part one) which i already did.. but at the same time to flip the bottom two lines (part two) so that it looks like this

JavaScript

again, i got the order and spacing taken care of, but how do i switch the bottom two lines (or flip them). by the way this can only be done with awk.

Advertisement

Answer

The following code switches the last two lines of a file:

JavaScript

To do so, we store the last three lines in an array. We print a line only when line after the next line is read. Finally, we take last two lines from the array, invert the order and print it.

A more detailed description of the code:
We store the content of the current line ($0) in an array. As we only need to keep track of the last three lines read, the index of our array can be limited to the values 0, 1, and 2. We achieve this by using the modulo operator (NR % 3).
When reaching the third line, we print the last but one line (if(NR>2)...). This is save, as in this case there are still two lines in the array that we can handle separately.
When the end of the file is reached (END{...}), we print the last two lines in inverse order.
Why did we use NR%3 (and not NR%2)? If there were only two lines in our input file, printing must happen in the END-block and not before!

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement