微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

sed仅在第一个匹配时插入

更新:

使用sed,我怎样才能在每个文件的关键字的第一个匹配上插入(不是SUBSTITUTE)一个新行。

目前我有以下,但这插入每一行包含匹​​配的关键字,我希望它只插入新插入的行只有在文件中find的第一个匹配:

sed -ie '/Matched Keyword/ iNew Inserted Line' *.*

例如:

Bash – 连接variables到path

用于从另一个文件的块组成文件的shell命令

Jupyter笔记本电脑没有正确启动在Windows Ubuntu的bash

Linux Bash autonumbering的文件名而不删除前导零

Shell脚本 – 批量循环

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

参数列表太长时如何正确使用“xargs”

随机select使用linux命令的列

如何用awk统计文件中的所有数字?

如何在C#中运行windows bash

Linux:WGET – scheme缺less使用-i选项

如果你想用sed *:

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

*仅适用于GNU sed

你可以在GNU sed中这样做:

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

但它不是便携式的。 由于可移植性好,这里是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 ,下面是一个简单的解决方案,它是纯粹的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 -i -e '/Matched Keyword/{iNew Inserted Line' -e ':a;$q;n;ba;}' *.*

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

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐