use*_*r27 64 linux bash shell awk sed
我想使用shell脚本将多行插入到文件中.让我们考虑一下我的输入文件内容是: input.txt:
abcd
accd
cdef
line
web
Run Code Online (Sandbox Code Playgroud)
现在我必须在input.txt文件中的'cdef'行后插入四行.插入我的文件后应该改变如下:
abcd
accd
cdef
line1
line2
line3
line4
line
web
Run Code Online (Sandbox Code Playgroud)
我应该使用shell脚本进行上面的插入.谁能帮我?
sat*_*sat 87
另一个sed,
sed '/cdef/r add.txt' input.txt
Run Code Online (Sandbox Code Playgroud)
input.txt中:
abcd
accd
cdef
line
web
Run Code Online (Sandbox Code Playgroud)
add.txt:
line1
line2
line3
line4
Run Code Online (Sandbox Code Playgroud)
测试:
sat:~# sed '/cdef/r add.txt' input.txt
abcd
accd
cdef
line1
line2
line3
line4
line
web
Run Code Online (Sandbox Code Playgroud)
如果要在input.txt文件中应用更改.然后,使用-i带sed.
sed -i '/cdef/r add.txt' input.txt
Run Code Online (Sandbox Code Playgroud)
如果要将正则表达式用作表达式,则必须使用-E标记sed.
sed -E '/RegexPattern/r add.txt' input.txt
Run Code Online (Sandbox Code Playgroud)
dev*_*ull 30
使用GNU sed:
sed "/cdef/aline1\nline2\nline3\nline4" input.txt
Run Code Online (Sandbox Code Playgroud)
如果你开始:
abcd
accd
cdef
line
web
Run Code Online (Sandbox Code Playgroud)
这会产生:
abcd
accd
cdef
line1
line2
line3
line4
line
web
Run Code Online (Sandbox Code Playgroud)
如果要将更改保存到文件中,请说:
sed -i "/cdef/aline1\nline2\nline3\nline4" input.txt
Run Code Online (Sandbox Code Playgroud)
Jan*_*eal 21
sed '/^cdef$/r'<(
echo "line1"
echo "line2"
echo "line3"
echo "line4"
) -i -- input.txt
Run Code Online (Sandbox Code Playgroud)
jay*_*ngh 13
使用awk:
awk '/cdef/{print $0 RS "line1" RS "line2" RS "line3" RS "line4";next}1' input.txt
Run Code Online (Sandbox Code Playgroud)
说明:
/.../print $0RS是内置awk变量,默认情况下设置为new-line.1最后导致所有其他线的打印.next之前使用它允许我们阻止当前行,因为您已经使用它来打印它print $0.
$ awk '/cdef/{print $0 RS "line1" RS "line2" RS "line3" RS "line4";next}1' input.txt
abcd
accd
cdef
line1
line2
line3
line4
line
web
Run Code Online (Sandbox Code Playgroud)
要对文件进行更改,您可以执行以下操作:
awk '...' input.txt > tmp && mv tmp input.txt
Run Code Online (Sandbox Code Playgroud)
这是一个基于@rindeal解决方案的更通用的解决方案 ,它不适用于 MacOS/BSD(/r需要一个文件):
cat << DOC > input.txt
abc
cdef
line
DOC
Run Code Online (Sandbox Code Playgroud)
$ cat << EOF | sed '/^cdef$/ r /dev/stdin' input.txt
line 1
line 2
EOF
# outputs:
abc
cdef
line 1
line 2
line
Run Code Online (Sandbox Code Playgroud)
这可用于将任何内容通过管道传输到给定位置的文件中:
$ cat << EOF | sed '/^cdef$/ r /dev/stdin' input.txt
line 1
line 2
EOF
# outputs:
abc
cdef
line 1
line 2
line
Run Code Online (Sandbox Code Playgroud)
此外,您可以添加多个允许删除标记线的命令cdef:
$ date | sed '/^cdef$/ r /dev/stdin' input.txt
# outputs
abc
cdef
Tue Mar 17 10:50:15 CET 2020
line
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
102408 次 |
| 最近记录: |