Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sed move a line

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.

like image 841
knuxyl Avatar asked Oct 24 '25 09:10

knuxyl


2 Answers

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
like image 94
William Pursell Avatar answered Oct 26 '25 02:10

William Pursell


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)

like image 29
mop Avatar answered Oct 26 '25 01:10

mop