【问题标题】:sed to insert on first match onlysed 仅在第一次匹配时插入
【发布时间】:2012-04-15 17:47:20
【问题描述】:

更新:

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

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

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

例如:

我的文件.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

【问题讨论】:

标签: linux bash sed


【解决方案1】:

如果你想要一个带有 sed* 的:

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

*仅适用于 GNU sed

【讨论】:

  • 这对我没有任何作用。
  • 啊,您的解决方案显然特定于 GNU sed。虽然还是错了,唉。
  • GNU sed version 4.2.1 一起为我工作。 @Squazic,也许您想限定您的答案。祝大家好运。
  • 这对我有用。我只是用新插入的行交换了匹配的关键字,因为我希望插入发生在匹配的关键字之前。感谢大家的投入。
【解决方案2】:

你可以在 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

或者,如果你想传递一个变量来打印:

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

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

【讨论】:

  • 在传统的 sed 中没有办法做到这一点吗?
  • 可以将 potong 的解决方案用于非 GNU sed。但它不会是单行的。我一般只做 sed 单线。 :-)
  • @Velthune - 一点也不,这是一个很好的补充。谢谢。 :)
【解决方案3】:

这可能对你有用:

sed -i -e '/Matched Keyword/{i\New Inserted Line' -e ':a;n;ba}' file

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

插入一行后,文件的其余部分可以通过以下方式打印出来:

  1. 引入循环占位符:a(这里a 是任意名称)。
  2. 使用ncommand 打印当前行并将下一行提取到模式空间中。
  3. 使用ba 命令将控制重定向回来,该命令本质上是gotoa 占位符。文件结束条件自然由n 命令处理,如果它试图读取通过文件结束符,它将终止任何进一步的 sed 命令。

在 bash 的帮助下,可以实现真正的单行:

sed $'/Matched Keyword/{iNew Inserted Line\n:a;n;ba}' file

替代方案:

sed 'x;/./{x;b};x;/Matched Keyword/h;//iNew Inserted Line' file

这使用Matched Keyword 作为保留空间中的标志,一旦设置,任何处理都会通过立即退出来减少。

【讨论】:

  • 嗯,是的,你能举一个完整的例子吗,因为我不确定如何在 sed 单行表达式中创建这个“循环”。
【解决方案4】:

如果您只想在第一次匹配后追加一行,请使用 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

【讨论】:

  • 你是如何做到这一点的?
猜你喜欢
  • 1970-01-01
  • 2018-11-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-30
  • 2015-05-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多