Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
511 views
in Technique[技术] by (71.8m points)

linux - sed to insert on first match only

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/ iNew 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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can sort of do this in GNU sed:

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

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 , 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...