我有一个小脚本可以执行一些操作global
各种文件中的字符串替换。这应该通过 sed
来完成以便仅更改受影响的行。
准备工作:
#!/bin/sh
find="Mücke Motorsport"
replace="Mücke Motorsport Racing Team"
file="/Users/meyer/Dropbox/Dev/App Framework iOS/dev/myfile.txt"
这是我在脚本中出现问题的行:
sed -i s/"$find"/"$replace"/g "$file"
不起作用(sed: 1: "/Users/meyer/Dropb ...": invalid command code o
)。下一步尝试:
sed -i 's/'"$find"'/'"$replace"'/g' "$file"
不起作用(sed: 1: "/Users/meyer/Dropb ...": invalid command code o
)。下一步尝试:
sed -i "s/$find/$replace/g" "$file"
不起作用(sed: 1: "/Users/meyer/Dropb ...": invalid command code o
)。下一步尝试:
sed -i s/$find/$replace/g "$file"
不起作用(sed: 1: "Motorsport/Mücke": invalid command code M
)。由于此错误消息,我尝试转义我的变量:
escaped_ find =$(printf '%s\n' "$find" | sed 's:[][\/.^$*]:\\&:g')
escaped_ replace =$(printf '%s\n' "$replace" | sed 's:[\/&]:\\&:g;$!s/$/\\/')
但是使用替换变量不起作用...我不知道如何让它工作:(
最佳答案
在 sed 的 OSX 版本上,-i 选项需要一个扩展参数,因此您的命令实际上被解析为扩展参数,并且文件路径被解释为命令代码。
尝试显式添加 -e 参数
sed -i'' -e 's/old/new/g' 文件
关于linux - sed 无法按预期使用脚本中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45712479/