• Uncategorized

About linux : Sed-move-a-line

Question Detail

I just need to move a line up in sed. I can select the line with

sed -i '7s///'

I need to move line 7 up 2 lines so it will be line 5.

I can’t find anything on the internet to do this without complicated scripts, I can’t find a simple solution of moving a specific line a specific number of times.

Question Answer

seq 10|sed '5{N;h;d};7G'

when up to line 5 append next line(line 6) into pattern space then save them into hold space and delete them from pattern space; up to line 7 then append the hold space content(“5\n6”) behind the line 7; now, pattern space is “7\n5\n6”;finally,sed will print the pattern space at the end of current cycle by default(if no “-n” parameter)

ed is better at this, since it has a “move” command that does exactly what you want. To move line 7 to be the line after line 4, just do 7m4. ed doesn’t write the data back by default, so you need to explicitly issue a w command to write the data:

printf '7m4\nw\n' | ed input

Although it is perhaps better to use a more modern tool:

ex -s -c 7m4 -c w -c q input

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.