Martin-
Martin-

Reputation: 927

sed append line on 1 occurrence only

Have this file

ServerName *
ServerAlias *
ServerAlias *

<Directory>

I want to append a new line after the first occurrence of ServerAlias with the text S2. I have tried the following

sed '/ServerAlias/ a\S2\' foo

But this appends after all the occurrences.

My final result should be

ServerName *
ServerAlias *
S2
ServerAlias *

<Directory>

Upvotes: 3

Views: 2638

Answers (2)

cmbuckley
cmbuckley

Reputation: 42517

The awk solution above is best, but if you really want to do it in (GNU) sed then the following does the trick:

sed '0,/^ServerAlias.\+/s//\0\nS2/' file

Credit goes to the sed FAQ.

Upvotes: 2

Actually, it's not sed, but maybe awk can help you.

$> cat ./file
ServerName *
ServerAlias *
ServerAlias *

<Directory>

$> awk '{print} /^ServerAlias/ && !n {print "S2"; n++}' ./file
ServerName *
ServerAlias *
S2
ServerAlias *

<Directory>

UPD: mistake is fixed now, thanks glenn_jackman

Upvotes: 5

Related Questions