[英]Insert multiple lines of text before specific line using Bash
我試圖在特定行之前插入幾行文本,但在嘗試添加新行字符時不斷出現sed錯誤。 我的命令看起來像:
sed -r -i '/Line to insert after/ i Line one to insert \\
second new line to insert \\
third new line to insert' /etc/directory/somefile.txt
報告的錯誤是:
sed: -e expression #1, char 77: unterminated `s' command
我試過,使用\\n
, \\\\
(如示例中所示),根本沒有字符,只是將第二行移動到下一行。 我也嘗試過類似的東西:
sed -r -i -e '/Line to insert after/ i Line one to insert'
-e 'second new line to insert'
-e 'third new line to insert' /etc/directory/somefile.txt
編輯!:道歉,我希望文本在現有之前插入,而不是之后!
這應該工作:
sed -i '/Line to insert after/ i Line one to insert \
second new line to insert \
third new line to insert' file
對於除了單獨行上的簡單替換之外的任何其他內容,使用awk而不是sed以簡化,清晰,穩健等等。
要在一行之前插入:
awk '
/Line to insert before/ {
print "Line one to insert"
print "second new line to insert"
print "third new line to insert"
}
{ print }
' /etc/directory/somefile.txt
要在一行之后插入:
awk '
{ print }
/Line to insert after/ {
print "Line one to insert"
print "second new line to insert"
print "third new line to insert"
}
' /etc/directory/somefile.txt
當要插入的行是某些命令“mycmd”(如cat results.txt
或printf "%s\\n" line{1..3}
)的結果時,你可以做
sed -i 's/Line to insert after/r' <(cmd) file
or
sed -i 's/Line to insert after/echo "&";cmd/e' file
如果要在某些匹配之前插入,可以簡單地修改最后一個命令。
sed -i '/Line to insert after/ i\
Line one to insert\
second new line to insert\
third new line to insert' /etc/directory/somefile.txt
這可能適合你(GNU sed&Bash):
sed -i $'/Line to insert after/a\line1\\nline2\\nline3' file
這將從第一行開始工作。例如:如果要從文件的第3行插入,請將“1i”替換為“3i”。
sed -i '1i line1'\\n'line2'\\n'line3' 1.txt
cat 1.txt
line1
line2
line3
Hai
為了符合POSIX並在OS X中運行,我使用了以下內容(單引號行和空行用於演示目的):
sed -i "" "/[pattern]/i\\
line 1\\
line 2\\
\'line 3 with single quotes\`
\\
" <filename>
這也可以通過Perl輕松完成
$ cat MeanwhileInHell.txt
Iran|XXXXXX|Iranian
Iraq|YYYYYY|Iraquian
Saudi|ZZZZZ|Saudi is a Rich Country
USA|AAAAAA|USA is United States of America.
India|IIII|India got freedom from British.
Scot|SSSSS|Canada Mexio.
$ perl -pe 'BEGIN {$x="Line one to insert\nLine 2\nLine3\n"} $_=$x.$_ if /USA/ ' MeanwhileInHell.txt
Iran|XXXXXX|Iranian
Iraq|YYYYYY|Iraquian
Saudi|ZZZZZ|Saudi is a Rich Country
Line one to insert
Line 2
Line3
USA|AAAAAA|USA is United States of America.
India|IIII|India got freedom from British.
Scot|SSSSS|Canada Mexio.
$
在MacOs我需要更多的東西。
i
后雙反斜杠 -i
后面的空引號指定無備份文件 此代碼在pom.xml中搜索</plugins
的第一個實例,並在其前面插入另一個XML對象,由換行符分隔。
sed -i '' "/\<\/plugins/ i \\
\ <plugin>\\
\ <groupId>org.apache.maven.plugins</groupId>\\
\ <artifactId>maven-source-plugin</artifactId>\\
\ <executions>\\
\ <execution>\\
\ <id>attach-sources</id>\\
\ <goals>\\
\ <goal>jar</goal>\\
\ </goals>\\
\ </execution>\\
\ </executions>\\
\ </plugin>\\
" pom.xml
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.