Jav*_*eva 108 sed text-processing
现在我正在使用
echo "Hello World" >> file.txt
Run Code Online (Sandbox Code Playgroud)
将一些文本附加到文件中,但我还需要在某个字符串下方添加文本,比如说[option],是否可以使用sed?
例如:
输入文件
Some text
Random
[option]
Some stuff
Run Code Online (Sandbox Code Playgroud)
输出文件
Some text
Random
[option]
*inserted text*
Some stuff
Run Code Online (Sandbox Code Playgroud)
Rah*_*til 146
匹配后追加行
sed '/\[option\]/a Hello World' input在匹配前插入行
sed '/\[option\]/i Hello World' input此外,您可以使用-i.bkpsed 选项就地备份和编辑输入文件
dev*_*ull 47
是的,可以使用sed:
sed '/pattern/a some text here' filename
Run Code Online (Sandbox Code Playgroud)
一个例子:
$ cat test
foo
bar
option
baz
$ sed '/option/a insert text here' test
foo
bar
option
insert text here
baz
$
Run Code Online (Sandbox Code Playgroud)
与awk:
awk '1;/PATTERN/{ print "add one line"; print "\\and one more"}' infile
Run Code Online (Sandbox Code Playgroud)
请记住,某些字符不能按字面意思包含,因此必须使用转义序列(它们以反斜杠开头),例如要打印字面反斜杠,必须写\\.
它实际上与 with 相同,sed但除此之外,文本中每个嵌入的换行符都必须以反斜杠开头:
sed '/PATTERN/a\
add one line\
\\and one more' infile
Run Code Online (Sandbox Code Playgroud)
有关转义序列的更多详细信息,请参阅手册。