用变量替换文本

发布于 2024-11-18 23:55:41 字数 194 浏览 6 评论 0原文

我想用变量替换该值。由于 sed 中使用了单引号,以下内容不起作用。

#!/bin/sh
set myvarM='pqr'
sed 's/:P03:M15/:P02:M1$myvarM/' mychange.txt > new_mychange.txt

我可以更改 sed 命令还是应该使用其他命令?

I want to replace the value with a variable. The following does not work because of the single quote used in sed.

#!/bin/sh
set myvarM='pqr'
sed 's/:P03:M15/:P02:M1$myvarM/' mychange.txt > new_mychange.txt

Can I change the sed command or should I use something else?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

年少掌心 2024-11-25 23:55:41
#!/bin/sh
myvarM='pqr'
sed "s/:P03:M15/:P02:M1$myvarM/" mychange.txt > new_mychange.txt

顺便说一句,要进行就地替换(即不创建新文件,而是更改原始文件),请执行以下操作:

sed -i '' "s/:P03:M15/:P02:M1$myvarM/" mychange.txt

这表示“使用空白作为增量后缀” - 即写出与输入相同的文件名

#!/bin/sh
myvarM='pqr'
sed "s/:P03:M15/:P02:M1$myvarM/" mychange.txt > new_mychange.txt

Incidentally, to make the replacement in-place (ie not create a new file, but alter the original file), do this:

sed -i '' "s/:P03:M15/:P02:M1$myvarM/" mychange.txt

This says "use a blank as the increment suffix" - ie write out the same filename as the input

可爱咩 2024-11-25 23:55:41
awk -v val="$myvarM" '{sub(/:P03:M15/, ":P02:M1" val); print}' filename

请注意,在 bourne 类型 shell (“/bin/sh”) 中,set 命令设置位置参数。您的第一行将 $1 设置为值 myvarM='pqr' —— myvarM 变量继续未设置。

awk -v val="$myvarM" '{sub(/:P03:M15/, ":P02:M1" val); print}' filename

Note that in a bourne-type shell ("/bin/sh") the set command sets the positional parameters. Your first line sets $1 to the value myvarM='pqr' -- the myvarM variable continues to be unset.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文