WanderingMind WanderingMind - 6 months ago 13
Bash Question

Move a line in a file from linenumber `n1` to linenumber `n2` in Unix

I have a file with name

file1
that looks as follows.

1 intst
2 1.0
3 12.591870 0.000000 0.000000
4 0.000000 12.591870 0.000000
5 0.000000 0.000000 12.591870
6 Ba Zr Al O
7 27 26 1 81
8 direct
9 0.166667 0.166666 0.167762 Ba
10 0.166667 0.166667 0.500000 Ba #Line to be moved
11 0.166666 0.166667 0.832238 Ba
...
...
60 0.666668 0.666666 0.329117 Zr
61 0.666665 0.666667 0.670884 Zr
62 0.666667 0.666667 1.000000 Al #Moved line to be inserted below this line
63 0.166667 0.999071 0.999999 O


I need to copy the contents of
line- 10
and move it below
line-62
by creating a new line so that the new filecontent appears as

1 intst
2 1.0
3 12.591870 0.000000 0.000000
4 0.000000 12.591870 0.000000
5 0.000000 0.000000 12.591870
6 Ba Zr Al O
7 27 26 1 81
8 direct
9 0.166667 0.166666 0.167762 Ba
10 0.166666 0.166667 0.832238 Ba #Original line- 11
...
...
59 0.666668 0.666666 0.329117 Zr
60 0.666665 0.666667 0.670884 Zr
61 0.666667 0.666667 1.000000 Al
62 0.166667 0.166667 0.500000 Ba #Original line-10
63 0.166667 0.999071 0.999999 O


Using sed I separately know how to delete a line

sed -i.bkp -e '10d' file


and to insert a line

sed -i '10i <string>'file1


But I'm not sure how to copy contents of a line and move it to another line

sat sat
Answer

You can use this sed:

sed '10{h;D}; 62G' file

As per comment by @Benjamin, you can also use d.

sed '10{h;d}; 62G' file

Use -i.bak for in-place edit.

Here,

  • 10 and 62 - Line number
  • h - Copy pattern space to hold space. This will save line 10 to hold space.
  • G - Append hold space to pattern space. This will append line 10 to pattern space.
  • D - Delete text in the pattern space up to the first newline.