Sed question

Hi,

I need to place a line of text into a file at a certain point, and I have been using:

sed '
/theWord/ {
a\
theNewLine
}' < sourceFile > newFile

This works a treat, trouble is that it adds theNewLine underneath EVERY occurrence of lines containing theWord. Does anyone know a way to simply add theNewLine underr the FIRST occurence of theWord, or indeed how to group multiple words together as theWord and add theNewLine under that?

Hope this is clear, thanks
:slight_smile:

You should be able to just replace /theWord/ with /a whole bunch of words/

If you know the words you're trying to replace are always on a certain line, such as line 2, you can use:

sed '
/several words/ {
2 a\
inserted line
}' < sourceFile > newFile

This is harder than it looks. The best that I can do is:
sed '
/theWord/ {
a\
theNewLine
:loop
n
b loop
}' < sourceFile > newFile

Okay, this is driving me nuts...

I wrote a script that would do what you need:

lineNum=`awk "/theWord/ {print NR;exit}" sourceFile`
sed '
/theWord/{
$lineNum a\
theNewLine
}' < sourceFile > newFile

Basically, the awk command is finding the first occurence of "theWord" in the file and storing the line number in the variable "lineNum".

This would work if only $lineNum would actually resolve to the line number, which it doesn't.. sed actually wants a number, such as 1 or 2, and not a variable.. oh well, it's a start if someone can figure out how to finish it..

If you're going to use a line number, there is no point to also use the pattern matching stuff. Just a line number in front of a "a" command will do it.

The problem that you are having is that you are putting a variable inside single quotes. The shell won't expand stuff inside single quotes. You need to move the line number outside of the quotes. The code you posted would work if you would just put a single quotes around the variable reference. This would give you a quoted string, then your variable outside of the quotes, and finally another quoted string.

Okay I gotcha .. cool

sed `awk "/theWord/ {print NR;exit}" sourceFile`' a\
theNewLine' < sourceFile > newFile