linux Command Line – How to Change Order of Lines in a File

command linelinuxtext processing

I'm trying to change the order of lines in a specific pattern. Working with a file with many lines (ex. 99 lines). For every three lines, I would like the second line to be the third line, and the third to be the second line.

EXAMPLE.

1- Input:

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

2- Output:

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

Best Answer

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.

Related Question