![](/img/trans.png)
[英]Find and replace inside a string variable using sed command - shell scripting
[英]Find and replace in shell scripting
是否可以使用shell搜索文件然后替换值? 当我安装服务时,我希望能够在配置文件中搜索变量,然后在该值中替换/插入我自己的设置。
当然,你可以使用sed或awk来做到这一点。 sed示例:
sed -i 's/Andrew/James/g' /home/oleksandr/names.txt
您可以使用sed执行搜索/替换。 我通常从bash shell脚本执行此操作,并将包含要替换为值的原始文件移动到新名称,并运行sed将输出写入我的原始文件名,如下所示:
#!/bin/bash
mv myfile.txt myfile.txt.in
sed -e 's/PatternToBeReplaced/Replacement/g' myfile.txt.in > myfile.txt.
如果未指定输出,则替换将转到stdout。
sed -i 's/variable/replacement/g' *.conf
您可以使用sed执行此操作:
sed -i 's/toreplace/yoursetting/' configfile
sed可能在每个类似unix的系统上都可用。 如果要替换多个出现,可以在s命令中添加ag:
sed -i 's/toreplace/yoursetting/g' configfile
请注意,如果未正确指定toreplace-value,则可能会完全破坏配置文件。 sed还支持搜索和替换中的正则表达式。
filepath="/var/start/system/dir1"
searchstring="test"
replacestring="test01"
i=0;
for file in $(grep -l -R $searchstring $filepath)
do
cp $file $file.bak
sed -e "s/$searchstring/$replacestring/ig" $file > tempfile.tmp
mv tempfile.tmp $file
let i++;
echo "Modified: " $file
done
通常使用像awk或sed这样的工具。
$ sed -i 's/ugly/beautiful/g' /home/bruno/old-friends/sue.txt
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.