在shell脚本中查找和替换

时间:2012-06-01 20:12:25

标签: linux shell scripting

是否可以使用shell搜索文件然后替换值?当我安装服务时,我希望能够在配置文件中搜索变量,然后在该值中替换/插入我自己的设置。

7 个答案:

答案 0 :(得分:25)

当然,你可以使用sed或awk来做到这一点。 sed例子:

sed -i 's/Andrew/James/g' /home/oleksandr/names.txt

答案 1 :(得分:8)

您可以使用sed执行搜索/替换。我通常从bash shell脚本执行此操作,并将包含要替换的值的原始文件移动到新名称,然后运行sed将输出写入我的原始文件名,如下所示:

#!/bin/bash
mv myfile.txt myfile.txt.in

sed -e 's/PatternToBeReplaced/Replacement/g' myfile.txt.in > myfile.txt.

如果您未指定输出,则替换将转到stdout。

答案 2 :(得分:2)

sed -i 's/variable/replacement/g' *.conf

答案 3 :(得分:1)

您可以使用sed执行此操作:

sed -i 's/toreplace/yoursetting/' configfile 

sed可能在每个类似unix的系统上都可用。如果要替换多个出现,可以在s命令中添加g:

sed -i 's/toreplace/yoursetting/g' configfile 

请注意,如果未正确指定toreplace-value,则会完全破坏配置文件。 sed还支持搜索和替换中的正则表达式。

答案 4 :(得分:1)

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

答案 5 :(得分:0)

通常使用像awk或sed这样的工具。

$ sed -i 's/ugly/beautiful/g' /home/bruno/old-friends/sue.txt

答案 6 :(得分:0)

使用Perl查看UNIX power tools awk,sed,grep in-place edit of files

相关问题