sed仅在第一场比赛中插入

时间:2012-04-02 02:08:15

标签: linux bash sed

更新:

使用sed,如何在每个文件的关键字的第一个匹配项上插入(NOT SUBSTITUTE)新行。

目前我有以下内容,但是这会插入包含匹配关键字的每一行,我希望它只为文件中找到的第一个匹配项插入新插入的行:

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

例如:

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

更改为:

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

4 个答案:

答案 0 :(得分:11)

如果你想要一个sed *:

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

*仅适用于GNU sed

答案 1 :(得分:8)

您可以在GNU sed中执行此操作:

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

但它不便携。由于可移植性很好,这里是awk:

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

或者,如果要将变量传递给print:

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

根据您的示例,这些都会在第一次出现关键字之前插入文本行,单独一行。

请记住,对于sed和awk,匹配关键字是正则表达式,而不仅仅是关键字。

<强>更新

由于此问题也标记为,因此这是一个纯粹的bash并且不需要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

就目前而言,这是一个管道。您可以轻松地将其包装在对文件起作用的内容中。

答案 2 :(得分:3)

这可能对您有用:

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

你快到了!只需创建一个循环即可从Matched Keyword读取到文件末尾。

答案 3 :(得分:0)

如果您想在第一场比赛后追加一条线,请使用AWK代替SED,如下所示

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

输出:

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