sed仅在第一场比赛中插入

SSS*_*SSS 17 linux bash sed

更新:

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

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

sed -ie '/Matched Keyword/ i\New Inserted Line' *.*
Run Code Online (Sandbox Code Playgroud)

例如:

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
Run Code Online (Sandbox Code Playgroud)

变成:

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
Run Code Online (Sandbox Code Playgroud)

gho*_*oti 14

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

sed '0,/Matched Keyword/s//New Inserted Line\n&/'
Run Code Online (Sandbox Code Playgroud)

但它不便携.既然可移植性很好,这里是awk:

awk '/Matched Keyword/ && !x {print "Text line to insert"; x=1} 1' inputFile
Run Code Online (Sandbox Code Playgroud)

或者,如果要传递变量进行打印:

awk -v "var=$var" '/Matched Keyword/ && !x {print var; x=1} 1' inputFile
Run Code Online (Sandbox Code Playgroud)

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

请记住,对于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
Run Code Online (Sandbox Code Playgroud)

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


Squ*_*zic 11

如果你想要一个sed*:

sed '0,/Matched Keyword/s//Matched Keyword\nNew Inserted Line/' myfile.txt
Run Code Online (Sandbox Code Playgroud)

*仅适用于GNU sed

  • 啊,你的解决方案显然特定于GNU sed.虽然它仍然是错的,唉. (4认同)
  • 这根本不对我有任何意义. (2认同)

pot*_*ong 5

这可能对你有用:

sed -i -e '/Matched Keyword/{i\New Inserted Line' -e ':a;n;ba}' file
Run Code Online (Sandbox Code Playgroud)

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

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

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

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

sed $'/Matched Keyword/{iNew Inserted Line\n:a;n;ba}' file
Run Code Online (Sandbox Code Playgroud)

选择:

sed 'x;/./{x;b};x;/Matched Keyword/h;//iNew Inserted Line' file
Run Code Online (Sandbox Code Playgroud)

这将Matched Keyword用作保持空间中的标志,一旦它被设置,任何处理都会通过立即退出来缩减。