简体   繁体   English

全局替换Shell脚本不起作用

[英]Global substitution shell script not working

I have a shell script like: 我有一个类似的shell脚本:

for fl in /home/dr/*.txt; do
mv $fl $fl.old
sed 's#$1#$2#g' $fl.old > $fl
rm -f $fl.old
done

and I run it like ./script.sh find replace , yet nothing happens and there is no output. 我像./script.sh find replace一样运行它,但是什么也没发生,也没有输出。 Why is this? 为什么是这样?

This might work for you (GNU sed): 这可能对您有用(GNU sed):

sed -i "s#$1#$2#g" /home/dr*.txt

The problem you had is single quotes around sed commands does not allow interpolation. 您遇到的问题是sed命令周围的单引号不允许插值。

The problem is that you're using single quotes instead of double quotes. 问题在于您使用的是单引号而不是双引号。 With single quotes, sed interprets the string literally (ie it will search for the string $1 , not the first argument). sed使用单引号直接解释字符串(即,它将搜索字符串$1 ,而不是第一个参数)。

Below is a functioning version of what you were trying to do. 以下是您尝试执行的功能版本。 Note that I've replaced temporary file usage with sed's "in-place" editing. 请注意,我已经用sed的“就地”编辑代替了临时文件的使用。

for fl in /home/dr/*.txt
do
  sed -i "s#$1#$2#g" $fl
done

However, you can one-line everything ! 但是, 您可以单行处理所有内容

sed -i "s#$1#$2#g" /home/dr/*.txt

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM