2012-04-02 126 views
7

更新:的sed插入上的第一场比赛只

使用SED,我怎么能插入(不能代替)的新行上为每个文件关键字只有第一场比赛。

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

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 
+0

[这个问题](HTTP的可能重复://堆栈溢出。com/q/148451/1086804) - 您可以通过使用换行符和反向引用来适应它。另见[本sed指南](http://www.linuxtopia.org/online_books/linux_tool_guides/the_sed_faq/sedfaq4_004.html) – 2012-04-02 02:18:13

回答

8

如果你想要一个与sed的*:

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

*只有GNU工程sed的

+1

这对我来说什么都不做。 – Graham 2012-04-02 03:37:10

+4

啊,你的解决方案显然是特定于GNU sed。虽然它仍然是错误的,唉。 – Graham 2012-04-02 03:39:45

+0

适用于'GNU sed version 4.2.1'。 @Squazic,也许你想限定你的答案。祝你们好运。 – shellter 2012-04-02 04:21:39

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 

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

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

这些都的第一次出现之前插入文本行关键字,在你自己的例子中,单独一行。

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

UPDATE:

由于这个问题也标记,这里有一个简单的解决方案,它是纯粹的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 

因为它的立场,这是一个管。您可以轻松地将其包装在代替文件的某些内容中。

+0

传统sed没有办法做到这一点吗? – Graham 2012-04-02 10:33:18

+0

可能适用于非GNU sed的potong解决方案。但它不会是一蹴而就的。我通常只做sed单线。 :-) – ghoti 2012-04-02 17:59:33

+0

+1与awk协同工作!谢谢 – 2014-07-23 07:48:38

2

这可能会为你工作:

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

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

+0

ummm,是的,你可以给一个完整的工作示例,因为我不知道如何在sed oneline表达式中创建这个“循环”。 – johnnyB 2013-10-29 20:15:19

+0

@johnnyB创建一个“循环”使用以下四个命令:':a'循环占位符,'$ q'当文件结束时退出(打印最后一行),'n'打印当前行和然后在下一个阅读和'ba'中断(转到)在这种情况下'a'的占位符。 – potong 2013-10-29 21:10:20

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 
+0

,你如何做到这一点? – sloven 2017-10-17 19:19:40