2012-04-02 55 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