I have a shell script like:
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. Why is this?
This might work for you (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.
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).
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.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.