sed命令中使用变量

有如下问题, 在使用sed命令替换文件内容时, 要替换的内容是动态的, 简化如下:

# 测试文件testfile.txt内容
# 目标: 将文件中的apple都替换成grape, apple和grape都是变量
$ cat testfile.txt; echo; echo "someFruit is: $someFruit";  echo "grape is: $grape";
fruits:
apple
banana
pear
apple

someFruit is: apple
grape is: grape

实现方法如下:

sed -i "s|$someFruit|$grape|g" testfile.txt

结果如下:

$ cat testfile.txt
fruits:
grape
banana
pear
grape

参考:
https://askubuntu.com/questions/76808/how-do-i-use-variables-in-a-sed-command


欢迎补充指正!

猜你喜欢

转载自blog.csdn.net/butterfly5211314/article/details/81635671