变量内的SED和特殊字符(Macos Monterey)

发布于 2025-02-10 19:48:38 字数 762 浏览 0 评论 0原文

我是外壳脚本和终端使用情况的新手。 我在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 技术交流群。

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

发布评论

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

评论(2

十年不长 2025-02-17 19:48:38

您可能需要为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@....@...@' or sed 's#...#...#'

But of course, this only works if the picked separator doesn't appear in your pattern/replacement.

口干舌燥 2025-02-17 19:48:38

没有人会记得seds之外的命令。例如,它还具有c to c hange a匹配行:

sed -i '' '/"PATH_VAR=.*"/c\
"PATH_VAR='"$PATH_VAR"'"
' file.txt

您的变量只需使用这种方法中没有任何新线。

Nobody ever remembers that sed has commands besides s. It also has, for example, c to change a matching line:

sed -i '' '/"PATH_VAR=.*"/c\
"PATH_VAR='"$PATH_VAR"'"
' file.txt

Your variable just needs to not have any newlines in it with this approach.

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