DMS
DMS

Reputation: 357

Telling sed where exactly to append a string

I am trying to edit a file that looks like this:

Separator line of dashes
Letters
Separator line of dashes
aaa
bbb

Separator line of dashes
Numbers
Separator line of dashes
111
222

The phrases between the dashes are supposed to be titles of sections.

With sed, I want to add a string like "000" to the "Numbers" section. The output would be:

Separator line of dashes
Numbers
Separator line of dashes
000
111
222

My question is: How do I tell sed that I want to append "000" as first line of section with title "Numbers"?

I have the following:

sed -i '/Numbers/ a\New ACE goes here' myFile

With that my line is added right below the title, but I need it actually 2 lines below.

For my future reference, how would it be if I want to tell sed, append this at a particular line number after matching "this line"?

Upvotes: 0

Views: 115

Answers (2)

Birei
Birei

Reputation: 36272

Using :

sed '/^Numbers/ { N; N; s/^\(.*\)\(\n\)/\1\2000\n/ }' infile

When it finds a line that matches Numbers, append the next two lines and add the 000 string just after the last newline character.

It yields:

Separator line of dashes
Letters
Separator line of dashes
aaa
bbb

Separator line of dashes
Numbers
Separator line of dashes
000
111
222

EDIT: Using a\ to append the new line without doing substitution, as asked in comments. Now only append the next line (N) after the matching Numbers because a\ appends with its own newline.

sed '/^Numbers/ { N; a\
000
}' infile

It yields same result.

Upvotes: 1

Birei
Birei

Reputation: 36272

It easier to do with . When first field matches Numbers, print that line, read next one (getline), print it and then print your line (000). The last print is the default for every other line of the input file:

awk '$1 ~ /Numbers/ { print; getline; print; print "000"; next } { print }' infile

It yields:

Separator line of dashes
Letters
Separator line of dashes
aaa
bbb

Separator line of dashes
Numbers
Separator line of dashes
000
111
222

Upvotes: 0

Related Questions