4

In Linux, say one wants to add the following line before line number five (thus line nuber 5 becomes line number 6) and wants to have all the lines in the output numbered throught the sed 'tool' =

sed -n '5\Insert this line before line nuber 29' FILE

Question: Where does = go in this construction for numbering the whole output's lines?

I know nl and cat --number and such, but as seditself provides a built-in tool for this, it would be nice to work with just one toolbox.

Update: This is what the result should look like, in some way or another: Every line with a number and the line above squeezed in the place of line number five etc.

1   A line
2   Another line
3   as abovr
4   again
5   Insert this line before line nuber 29
6   This originally was line number 5
7   nearing the end
8   last line
1
  • 1
    sed numbers input lines - the ones which it cycles over - it doesnt number output lines. you can insert that anywhere you want - that line wont get its own number. try seq 10|sed '=;y/150/\n\n\n/;=' to see what i mean. theres nothing stopping you from doing sed 'a\some new line' <in | sed = though, of course.
    – mikeserv
    Dec 5, 2014 at 8:59

1 Answer 1

4

Using = will print the line number, and on a new line the line:

~$ sed '=' myfile
1
a
2
b
3
c
4
d
5
e
6
f
7
g
8
h

If you use two invocations of sed, you can print on the same line:

~$ sed '=' myfile | sed '{N;s/\n/ /}'
1 a
2 b
3 c
4 d
5 e
6 f
7 g
8 h

And you can one more to insert the line using the i \ command:

$ sed '5 i\
before 5
' myfile | sed '=' | sed '{N;s/\n/ /}'
1 a
2 b
3 c
4 d
5 before 5
6 e
7 f
8 g
9 h

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .