16

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.

Amanada Smith
  • 1,893
  • 9
  • 28
  • 42

7 Answers7

31

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

sed -i 's/Andrew/James/g' /home/oleksandr/names.txt
Oleksandr Kravchuk
  • 5,963
  • 1
  • 20
  • 31
  • 8
    Could you also please explain the command? also maybe give a reference to what sed means? and -i and s and g? – Daniel Jun 19 '19 at 11:09
  • 1
    @Daniel, sed mean stream editor, it is a utility to process text in linux. You can find out more about it by look at the man page with command `man sed` in linux. -i mean do replace inplace, s mean search and replace action, g mean do it globally (not once). Hope that it help – Joanna Apr 27 '21 at 03:49
12

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.

octopusgrabbus
  • 10,555
  • 15
  • 68
  • 131
2
sed -i 's/variable/replacement/g' *.conf
reuben
  • 3,360
  • 23
  • 28
embedded.kyle
  • 10,976
  • 5
  • 37
  • 56
1

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.

Flashpix
  • 166
  • 9
1

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

Vidul
  • 10,128
  • 2
  • 18
  • 20
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
Raktim Biswas
  • 4,011
  • 5
  • 27
  • 32
user68775
  • 11
  • 1
  • Could you check the `enter code here` in your code? It probably should not be there. By the way: In most cases it's a good idea to supply comments in your solution or at least to summarize the approach that you chose tackle the problem. – Marcus Rickert Jun 01 '14 at 22:35
0

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

$ sed -i 's/ugly/beautiful/g' /home/bruno/old-friends/sue.txt
Paulo Scardine
  • 73,447
  • 11
  • 124
  • 153