2011-06-08 82 views
22

如何在模式之前和行號之後使用sed將一行插入文件?以及如何在shell腳本中使用它們?如何在模式之前和行號之後使用sed插入一行?

這將插入符合模式的每行前:

sed '/Sysadmin/i \ Linux Scripting' filename.txt 

,這將改變這種使用行數範圍:那麼現在如何使用這些兩(這我不能」

sed '1,$ s/A/a/' 

t)在模式之前和行號或其他方法之後使用sed將一行插入文件?

回答

21

您可以編寫一個sed腳本文件,並使用:

sed -f sed.script file1 ... 

或者你可以用(多個)-e 'command'選項:

sed -e '/SysAdmin/i\ 
Linux Scripting' -e '1,$s/A/a/' file1 ... 

如果你想有一個行之後追加的東西,那麼:

sed -e '234a\ 
Text to insert after line 234' file1 ... 
+0

所以喬納森,如果我有XML這種格式:<供應商名稱= 「XEROX CORPORATION」>

解釋 - 上述新線=「000000」description =「XEROX CORPORATION」/> 如何在標籤前使用sed添加一行「」? – Nohsib 2011-06-08 21:41:13

+0

我想通了,謝謝你的幫助:sed -i -e'8,$ s/<\/vendor>/testing /'-e'/ testing/i \ '-e'8,$ s/testing/<\/vendor> /'vendors1.xml – Nohsib 2011-06-08 21:54:11

+0

讓我得到這個工作到位,我不得不做'sed -i'22a我在第22行添加的文本' test.txt' – jamescampbell 2017-10-29 21:46:07

7

我假設你想要在模式之前插入行只有當cur租用線路號碼大於某個值(即如果行號之前發生的模式,什麼也不做)

如果你不依賴於sed

awk -v lineno=$line -v patt="$pattern" -v text="$line_to_insert" ' 
    NR > lineno && $0 ~ patt {print text} 
    {print} 
' input > output 
+0

+1:我想知道這個問題是否應該如何解釋,但給出了更簡單的答案,這似乎是有幫助的。在sed中很難實現這種效果 - 可能不是不可能的,但涉及嵌套命令等等。 – 2011-06-09 14:44:21

0

這裏是如何在一個文件中的行前插入一行的例子:

例如文件test.txt:

hello line 1 
hello line 2 
hello line 3 

腳本:

sed -n 'H;${x;s/^\n//;s/hello line 2/hello new line\n&/;p;}' test.txt > test.txt.2 

輸出文件test.txt.2

hello line 1 
hello new line 
hello line 2 
hello line 3 

NB!請注意,sed已經開始將換行換成無空格 - 這是必要的,否則結果文件將在開頭有一個空行

腳本查找包含「hello line 2」的行,然後插入

sed -n: 
suppress automatic printing of pattern space 

H;${x;s/test/next/;p} 

/<pattern>/ search for a <pattern> 
${} do this 'block' of code 
H put the pattern match in the hold space 
s/ substitute test for next everywhere in the space 
x swap the hold with the pattern space 
p Print the current pattern hold space. 
相關問題