kilojoules kilojoules - 3 months ago 6
Bash Question

How can I shift a line down in shell?

How can I shift a line down in shell, based on it's line number?

For an example file ex.file,

stuff
other stuff
I want this line to go down one
more stuff
more stuff


I would want this file to be changed so that it reads:

stuff
other stuff
more stuff
I want this line to go down one
more stuff

Answer

You can use awk:

awk -v n=3 'NR==n{line=$0; next} NR==n+2{print line} 1' file

stuff
other stuff
more stuff
I want this line to go down one
more stuff

To save changes back to file using gnu awk:

awk -i inplace -v n=3 'NR==n{line=$0; next} NR==n+2{print line} 1' file

If not using gnu awk then

awk -v n=3 'NR==n{line=$0; next} NR==n+2{print line} 1' file > _file.tmp &&
mv _file.tmp file
Comments