使用 sed 将文件中的一行替换为来自 stdin 或 HEREDOC 的多行 [英] use sed to in-place replace a line in a file with multiple lines from stdin or HEREDOCs

查看:63
本文介绍了使用 sed 将文件中的一行替换为来自 stdin 或 HEREDOC 的多行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用多行替换文件中的一行.我知道我可以在 sed 替换中使用 \n ,但这相当丑陋.我希望听到 HEARDOC.

I want to replace a line in a file with multiple lines. I know I can use \n in the sed replace, but that is rather ugly. I was hoping to HEARDOCs.

所以我可以这样做用多行替换该行:

So I can do this to replace the line with multiple lines:

$ cat sedtest
DINGO=bingo

$ sed -i -e "s/^DINGO.*$/# added by $(whoami) on $(date)\nDINGO=howdy/" sedtest

$ cat sedtest
# added by user on Sun Feb  3 08:55:44 EST 2019
DINGO=howdy

在命令中,我想将替换内容放在新行中,以便更容易阅读/理解.到目前为止,当我想在文件中添加新行时,我一直在使用 HEREDOC:

In the command I want to put the replacement in new lines so it's easier to read/understand. So far I have been using HEREDOCs when I want to add new lines to a file:

CAT << EOF | sudo tee -a file1 file2 file3
line one
line two
line three
EOF

这对于追加/添加很有效.是否可以做类似的事情,而是使用输出作为 sed 中的替代品,还是有其他方法可以做我正在寻找的东西?

And this has worked well for appending/adding. Is it possible to do something similar but instead use the output as the replacement in sed or is there some other way to do what I'm looking for?

推荐答案

这是您想要做的吗?

$ awk 'NR==FNR{new=(NR>1?new ORS:"") $0;next} $0=="DINGO=bingo"{$0=new} 1' - file <<!
# added by $(whoami) on $(date)
DINGO=howdy
!
# added by user on Sun, Feb  3, 2019  8:50:41 AM
DINGO=howdy

请注意,上面使用的是文字字符串操作,因此它适用于旧字符串或新字符串中的任何字符,这与您的 sed 脚本不同,在给定 /s 或任何 ERE 正则表达式字符或捕获时会失败组或反向引用或...在输入中(有关详细信息,请参阅是否可以使用 sed 可靠地转义正则表达式元字符).

Note that the above is using literal string operations so it'll work for any characters in the old or new strings unlike your sed script which would fail given /s or any ERE regexp character or capture groups or backreferences or... in the input (see Is it possible to escape regex metacharacters reliably with sed for details).

这篇关于使用 sed 将文件中的一行替换为来自 stdin 或 HEREDOC 的多行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆