Change the order of lines in a file

$ seq 9 | sed -n 'p;n;h;n;G;p'
1
3
2
4
6
5
7
9
8

That is, print the current line, get the next one, hold it, get the next one, Get the held line (append it to the pattern space) and print that 2-line pattern space with the third and second lines swapped.


Using awk and integer maths:

awk 'NR%3 == 1 { print } NR%3 == 2 { delay=$0 } NR%3 == 0 { print; print delay; delay=""} END { if(length(delay) != 0 ) { print delay } }' /path/to/input

The modulus operator performs integer division and returns the remainder, so for each line, it will return the sequence 1, 2, 0, 1, 2, 0 [...]. Knowing that, we just save the input on lines where the modulus is 2 for later -- to wit, just after printing the input when it's zero.


Another awk approach:

awk '{print $0; if ((getline L2)>0 && (getline L3)>0){ print L3 ORS L2 }}' file

The output:

gi_1234
I have a cat.
My cat is blue.
gi_5678
I also have a dog.
My dog is orange.

  • (getline L2)>0 && (getline L3)>0 - extracts next 2 records if they exist

  • each 2nd and 3rd records are assigned to L2 and L3 variables respectively