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 bash , 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.
ghoti
source share