3

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>
Martin-
  • 876
  • 2
  • 13
  • 30

2 Answers2

5

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

2

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.

cmbuckley
  • 40,217
  • 9
  • 77
  • 91
  • It was some buggy if I repeated the command multiple times. Probably, it depends from OS lindendings. Instead, I used ServerName as a target, to add a ServerAlias after. – Fedir RYKHTIK Mar 25 '13 at 10:30
  • Related to the potential line ending issue: http://stackoverflow.com/questions/6111679/insert-linefeed-in-sed – cmbuckley Mar 25 '13 at 12:21