stdcerr
stdcerr

Reputation: 15608

insert a line using sed

I have an ini file looking like:

...
abc = 123
def = 456
...

and I would like to change this to:

...
abc = 123
xyz = 987
def = 456
...

I've unsuccesfully tried this: sed -i 's/abc = 123\ndef = 456/abc = 123\nxyz = 987\ndef = 456/g' myfile.ini How do I fix my call to sed for this to work?

Upvotes: 0

Views: 58

Answers (4)

Thor
Thor

Reputation: 47099

Here is a portable way of appending a line after a pattern:

<myfile.ini sed '/abc = 123/a\
xyz = 789
'

Output:

abc = 123
xyz = 789
def = 456

Upvotes: 0

SLePort
SLePort

Reputation: 15461

Another approach with sed:

sed '/abc = 123/N;s/\ndef = 456/\nxyz = 987&/' myfile.ini

Upvotes: 2

lioumens
lioumens

Reputation: 120

Sed naturally looks at only a single line, so it won't find the '\n' character as you want it to. The easiest solution is to replace all '\n' with another temporary character like '\f' (form feed character).

Here's the hackish method I've been using. (separated for clarity)

cat myfile.ini |
tr '\n' '\f' |
sed -e "s/abc = 123\fdef = 456/abc = 123\fxyz = 987\fdef = 456/g" |
tr '\f' '\n'

'\f' is the form feed character. If you are on MacOS, you will need to replace all '\f' with $(printf '\f') in the sed statement.

Note: I would also recommend using sed grouping syntax to make your patterns easier to read.

It's hard to do multiline edits with sed. You should look into perl for more complex edits.

Upvotes: 0

glenn jackman
glenn jackman

Reputation: 246827

sed '
    /^def / {     # if this line matches the  2nd pattern
        x         # swap this line and the hold space
        /^abc / { # if this line matches the 1st pattern
                  # insert the new line
            i\
xyz = 987
        }
        x         # re-swap this line and the hold space
    }
    h             # put this line into the hold space
' file.ini

Upvotes: 2

Related Questions