英文:
bash sed truncates file instead of replacing text
问题
bash sed截断文件而不是替换文本。
我想要使用sed在bashrc源中更新变量,但令我惊讶的是,sed截断了文件。
为了测试,我有一个小文件abc:
export PATH=$PATH:$HOME/bin:$JAVA_HOME/bin
export myip=1.2.3.4
以及这个测试脚本:
#!/bin/bash
myip=1.2.3.4; newip=5.6.7.8
sed -ni 's/$myip/$newip/' abc
运行该脚本会使abc文件变为空。为什么会这样?
我在Intel I7上使用Ubuntu 22.04。
英文:
bash sed truncates file instead of replacing text.
I want to update variables in bashrc source with sed but to my surprise sed truncates the file.
For testing i have a little file abc:
export PATH=$PATH:$HOME/bin:$JAVA_HOME/bin
export myip=1.2.3.4
and this test script:
#!/bin/bash
myip=1.2.3.4; newip=5.6.7.8
sed -ni 's/$myip/$newip/' abc
running the script leaves abc empty.
Why is this so?
I am using Ubuntu 22.04 on an Intel I7.
答案1
得分: 1
这是因为您使用的引号、-n 选项以及替代物后面没有 p。
在 bash 中,单引号 ' 确保文本被字面解释,不进行变量扩展。因此,您可能希望使用双引号 "。
因为您使用了 -n,所以您可能还想使用 p 打印要保留的行:
sed -ni "s/$myip/$newip/p" abc
请注意,如果您想保留不匹配的行,只需删除 -n。
还要注意,您的 myip 模式中的 . 匹配任何字符。因此,您的模式 1.2.3.4 将匹配 IP 地址 112.3.4.9 中的 112.3.4 部分,然后变为 5.6.7.8.9。
英文:
That is because of the quotes that you use, the -n option and the absence of a p behind the substitute.
In bash, the single quote ' makes sure that the text is taken literally, without variable expansion. So, you would probably want to use double quotes ".
Because yo use -n, you will probably want to print the line that you want to keep as well with the p:
sed -ni "s/$myip/$newip/p" abc
Note that, if you want to keep the lines that do not match, you just remove the -n.
Note too that the . in your myip pattern matches any character. So, your pattern 1.2.3.4 will match the 112.3.4 part of the IP address 112.3.4.9, which will then become 5.6.7.8.9.
答案2
得分: 0
你的脚本中有两个错误。
-
当你将字符串括在单引号
'中时,不会发生bash变量的替换。你需要使用双引号"。 -
如果你使用
-n选项,除了你不使用的p命令之外,不会产生任何输出。
正确的脚本是:
#!/bin/bash
myip=1.2.3.4; newip=5.6.7.8
sed -i "s/$myip/$newip/" abc
英文:
There are two errors in your script.
-
When you enclose a string into single quotes
', the substitution of the bash variables will not happen. You have to use double quotes". -
If you use the
-noption, you will produce no output except with the commandpthat you don't use.
The correct script is:
#!/bin/bash
myip=1.2.3.4; newip=5.6.7.8
sed -i "s/$myip/$newip/" abc
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论