Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sed - append to next line using command line

I wish to append " dddd" to the next line whenever I encounter "=" in a textfile.

This command

sed -i '/=/s|$| dddd|' *.krn

is close to what I am looking for as it appends to the current line where "=" is. How can I append to the next line instead?

like image 915
Michael Ward Avatar asked May 21 '26 10:05

Michael Ward


2 Answers

Use append, see here:

  • http://www.grymoire.com/Unix/Sed.html#uh-40

E.g.:

$ echo $'abc\ndef\ne=f\nqqq'
abc
def
e=f
qqq
$ echo $'abc\ndef\ne=f\nqqq'|sed '/=/adddd'
abc
def
e=f
dddd
qqq

Edited to clarify as per comment from @je4d- if you want to append to what is present in the next line, you can use this:

$ echo $'abc\ndef\ne=f\nqqq\nyyy'
abc
def
e=f
qqq
yyy
$ echo $'abc\ndef\ne=f\nqqq\nyyy'|sed '/=/{n;s/$/ dddd/}'
abc
def
e=f
qqq dddd
yyy

See here for a great sed cheatsheet for more info if you want:

  • http://www.catonmat.net/download/sed.stream.editor.cheat.sheet.txt
like image 113
icyrock.com Avatar answered May 23 '26 08:05

icyrock.com


So to reiterate the question, when you match on one line, you want to append a string to the next line---a line that already exists, rather than adding a new line after it with the new data.

I think this will work for you:

sed '/=/ { N; s/$/ ddd/ }'

Say you have a file like:

=
hello
world
=
foo
bar
=

Then processing this command on it will yield:

=
hello ddd
world
=
foo ddd
bar
=

The trick here is using the N command first. This reads in the "next" line of input. Commands following it will be applied to the next line.

like image 33
imm Avatar answered May 23 '26 08:05

imm