Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sed to insert on first match only

Tags:

UPDATED:

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

Currently I have the following but this inserts for every line containing Matched Keyword and I want it to only insert the New Inserted Line for only 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
like image 754
SSS Avatar asked Apr 02 '12 02:04

SSS


People also ask

How do you insert a sed line after a pattern?

You have to use the “-i” option with the “sed” command to insert the new line permanently in the file if the matching pattern exists in the file.

How do you use sed to replace the first occurrence in a file?

With GNU sed's -z option you could process the whole file as if it was only one line. That way a s/…/…/ would only replace the first match in the whole file. Remember: s/…/…/ only replaces the first match in each line, but with the -z option sed treats the whole file as a single line.


Video Answer


1 Answers

You can sort of do this in GNU sed:

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

But it's 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

These both insert the text line before the first occurrence of the keyword, on a line by itself, per your example.

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

UPDATE:

Since this question is also tagged bash, here's a simple solution that is pure bash and doesn't required 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

As it stands, this as a pipe. You can easily wrap it in something that acts on files instead.

like image 62
ghoti Avatar answered Dec 01 '22 18:12

ghoti