Find and replace in shell scripting

只愿长相守 提交于 2019-12-31 10:01:47

问题


Is it possible to search in a file using shell and then replace a value? When I install a service I would like to be able to search out a variable in a config file and then replace/insert my own settings in that value.


回答1:


Sure, you can do this using sed or awk. sed example:

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



回答2:


You can use sed to perform search/replace. I usually do this from a bash shell script, and move the original file containing values to be substituted to a new name, and run sed writing the output to my original file name like this:

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

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

If you don't specify an output, the replacement will go to stdout.




回答3:


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



回答4:


You can use sed to do this:

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

sed is probably available on every unix like system out there. If you want to replace more than one occurence you can add a g to the s-command:

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

Be careful since this can completely destroy your configfile if you don't specify your toreplace-value correctly. sed also supports regular expressions in searching and replacing.




回答5:


Look at the UNIX power tools awk, sed, grep and in-place edit of files with Perl.




回答6:


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



回答7:


Generally a tool like awk or sed are used for this.

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


来源:https://stackoverflow.com/questions/10856749/find-and-replace-in-shell-scripting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!