Find and replace shell scripts

Is it possible to search the file using the shell and then replace the value? When I install the service, I would like to be able to search for a variable in the configuration file, and then replace / insert my own settings into this value.

+10
linux scripting shell
source share
8 answers

Of course, you can do this with sed or awk. Sed example:

sed -i 's/Andrew/James/g' /home/oleksandr/names.txt 
+25
source share

You can use sed to do a search / replace. I usually do this from the bash shell and move the source file containing the values ​​that need to be replaced with a new name and run sed, writing the output to the original file name as follows:

 #!/bin/bash mv myfile.txt myfile.txt.in sed -e 's/PatternToBeReplaced/Replacement/g' myfile.txt.in > myfile.txt. 

If you do not specify output, the replacement will be passed to standard output.

+8
source share
 sed -i 's/variable/replacement/g' *.conf 
+2
source share

You can use sed for this:

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

sed is probably available on any UNIX system. If you want to replace several cases, you can add g to the s command:

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

Be careful, as this can completely destroy your configuration file if you did not specify the correct value for your file. sed also supports regular expressions when searching and replacing.

+1
source share

Check out UNIX electronics tools awk, sed, grep and in-place file editing with Perl.

+1
source share
 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 
+1
source share

Usually a tool like awk or sed is used for this.

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

Could you also explain the team? also possibly give a link what does sed mean? and -i and s and g? - Daniel June 19 at 11:09

Unfortunately, I do not have enough representatives to answer your comment, so I have to do it this way. This is better explained in this thread:

Find and replace inside a text file using the Bash command

0
source share

All Articles