Sed to insert for first match only

UPDATED:

Using sed, how can I insert (NOT SUBSTITUTE) a new line for only the first keyword match for each file.

Currently, I have the following, but these inserts for each line containing a matching keyword, and I want it to only insert a new inserted row for the first match found in the file:

sed -ie '/Matched Keyword/ i\New Inserted Line' *.* 

For example:

Myfile.txt:

 Line 1 Line 2 Line 3 This line contains the Matched Keyword and other stuff Line 4 This line contains the Matched Keyword and other stuff Line 6 

changed to:

 Line 1 Line 2 Line 3 New Inserted Line This line contains the Matched Keyword and other stuff Line 4 This line contains the Matched Keyword and other stuff Line 6 
+7
source share
4 answers

If you want one with sed *:

 sed '0,/Matched Keyword/s//Matched Keyword\nNew Inserted Line/' myfile.txt 

* only works with GNU sed

+8
source

You can do this in GNU sed:

 sed '0,/Matched Keyword/s//New Inserted Line\n&/' 

But this is not portable. Since portability is good, here it is in awk:

 awk '/Matched Keyword/ && !x {print "Text line to insert"; x=1} 1' inputFile 

Or, if you want to pass a variable to print:

 awk -v "var=$var" '/Matched Keyword/ && !x {print var; x=1} 1' inputFile 

They both insert a text string before the first entry of the keyword into the string separately according to your example.

Remember that with sed and awk, the matched keyword is a regular expression, not just a keyword.

UPDATE:

Since this question is also tagged with , here is a simple solution, pure bash and not requiring sed:

 #!/bin/bash n=0 while read line; do if [[ "$line" =~ 'Matched Keyword' && $n = 0 ]]; then echo "New Inserted Line" n=1 fi echo "$line" done 

Like him, it's like a pipe. You can easily wrap it with what acts on files.

+8
source

This might work for you:

 sed -i -e '/Matched Keyword/{i\New Inserted Line' -e ':a;$q;n;ba;}' *.* 

You are almost there! Just create a loop to read from the Matched Keyword to the end of the file.

+2
source

If you want to add a line after the first match, use AWK instead of SED, as shown below

 awk '{print} /Matched Keyword/ && !n {print "New Inserted Line"; n++}' myfile.txt 

Output:

 Line 1 Line 2 Line 3 This line contains the Matched Keyword and other stuff New Inserted Line Line 4 This line contains the Matched Keyword and other stuff Line 6 
0
source

All Articles