变量内的SED和特殊字符(Macos Monterey)
我是外壳脚本和终端使用情况的新手。 我在ZSH脚本中具有跟踪行,其中path_var
始终是我必须插入的绝对文件夹路径:
#!/bin/zsh
...
read PATH_VAR
sed -i "" "s/\"PATH_VAR=.*\"/\"PATH_VAR=$PATH_VAR\"/" file.txt
...
这个想法是替换文本文件上的可变值我想替换为(“包括”):
"PATH_VAR=/Path/to/folder"
我将变量设置为例如/path/to/folder
;关注行弹出:
sed: line: "s/\"PATH_VAR=.*\"/\"P ...": bad flag in substitute command: 'P'
我知道这是由于/
通过sed
;实际上,当我运行时:
sed -i "" "s/\"PATH_VAR=.*\"/\"PATH_VAR=\/Path\/to\/folder\"/" file.txt
一切都会顺利进行,并且弦被更换。 我想知道是否有解决方法。由于path_var
始终是绝对的路径,因此我考虑在path_var
variable中发现的每个///condibal ofsive 。这是否可以使用sed
?
I'm new to shell scripting and Terminal usage.
I have the follow line of code in a zsh script, where the PATH_VAR
is always an absolute folder path that I have to insert:
#!/bin/zsh
...
read PATH_VAR
sed -i "" "s/\"PATH_VAR=.*\"/\"PATH_VAR=$PATH_VAR\"/" file.txt
...
The idea is to replace the variable value on a text file, where the string I want to replace is ("" included):
"PATH_VAR=/Path/to/folder"
I set the variable as, for example, /Path/to/folder
; the follow line pops out:
sed: line: "s/\"PATH_VAR=.*\"/\"P ...": bad flag in substitute command: 'P'
I understand that this is due to the /
that gets interpreted differently by sed
; in fact when I run:
sed -i "" "s/\"PATH_VAR=.*\"/\"PATH_VAR=\/Path\/to\/folder\"/" file.txt
everything goes smoothly and the string gets replaced.
I want to know if there's a workaround. Since the PATH_VAR
is always an absolute path, I thought about recoursively adding the \ before every / that is found in the PATH_VAR
variable. Is this possible with sed
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可能需要为SED的
s
命令选择另一个分隔符,而不是努力逃脱这些斜线。例如sed's@....@...@...@'
或sed's#...#...#'
当然,这只有在您的图案/替换中没有出现时,才能有效。
Instead of struggling to escape those slashes, you may want to pick another separator for sed's
s
command. E.g.sed 's@....@...@'
orsed 's#...#...#'
But of course, this only works if the picked separator doesn't appear in your pattern/replacement.
没有人会记得
sed
除s
之外的命令。例如,它还具有c
to c hange a匹配行:您的变量只需使用这种方法中没有任何新线。
Nobody ever remembers that
sed
has commands besidess
. It also has, for example,c
to change a matching line:Your variable just needs to not have any newlines in it with this approach.