gpt4 book ai didi

bash - 用 Bash 变量替换 sed

转载 作者:太空宇宙 更新时间:2023-11-04 13:01:59 24 4
gpt4 key购买 nike

我正在尝试在 Bash 脚本中使用 sed 更改文本文件中的值,

sed 's/draw($prev_number;n_)/draw($number;n_)/g' file.txt > tmp

这将在 for 循环中。为什么它不起作用?

最佳答案

' 中的变量不会在 Bash 中被替换。要进行字符串替换(或插值,如果您熟悉 Perl),您需要将其更改为使用双引号 " 而不是单引号:

# Enclose the entire expression in double quotes
$ sed "s/draw($prev_number;n_)/draw($number;n_)/g" file.txt > tmp

# Or, concatenate strings with only variables inside double quotes
# This would restrict expansion to the relevant portion
# and prevent accidental expansion for !, backticks, etc.
$ sed 's/draw('"$prev_number"';n_)/draw('"$number"';n_)/g' file.txt > tmp

# A variable cannot contain arbitrary characters
# See link in the further reading section for details
$ a='foo
bar'
$ echo 'baz' | sed 's/baz/'"$a"'/g'
sed: -e expression #1, char 9: unterminated `s' command

进一步阅读:

关于bash - 用 Bash 变量替换 sed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33646610/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com