sed 用多行变量替换行 [英] sed replace line with multiline-variable

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

问题描述

我正在尝试用存储在变量中的多行字符串替换文件中的单行.

I'm trying to replace a single line in a file with a multiline string stored in a variable.

打印到屏幕时我能够获得正确的结果,但如果我想进行就地替换则不行.

I am able to get the correct result when printing to screen, but not if I want to do an in-place replacement.

文件有格式:

*some code*
*some code*
string_to_replace
*some code*

我希望生成的文件是:

*some code*
*some code*
line number 1
line number 2
line number 3
*some code*

我试过的代码是:

new_string="line number 1\nline number 2\nline number 3"

# Correct output on screen
sed -e s/"string_to_replace"/"${new_string}"/g $file

# Single-line output in file: "line number 1line number 2line number 3"
sed -i s/"string_to_replace"/"${new_string}"/g $file

尝试组合 -i-e 选项时,结果与仅使用 -i 时相同.

When trying to combine -i and -e options, the result is the same as when only using -i.

我在 CentOS 上使用 GNU sed 4.1.5 版(通过 Mac 上的 ssh 连接到它).

I'm using GNU sed version 4.1.5 on CentOS (connected to it through ssh from Mac).

推荐答案

sed 中,您可以将命令字符串双引号并让 shell 为您进行扩展,如下所示:

In sed you can double quote the command string and let the shell do the expansion for you, like this:

new_string="line number 1\nline number 2\nline number 3"
sed -i "s/string_to_replace/$new_string/" file

这篇关于sed 用多行变量替换行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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