bash script to change texts in a list of files

AXISHK
AXISHK used Ask the Experts™
on
I need to write a scrpt to change some text for all files stored under a particular directory and sub-directories. The script will read a file (replace.txt) and change the context of each file based on it. The file will have the following format :

replace.txt
/eng               /chi
engwrd         chiwrd
/oci/pass      /bci/pass

Is it possible to archieve this through a bash script ?

Tks
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
#!/bin/bash
while read line; do
        word=`echo $line | awk '{print $1}'`
        newword=`echo $line | awk '{print $2}'`

echo "WORD is $word"
echo "Replace WORD with $newword"

find /var/tmp/test -type f | xargs sed -i "s#$word#$newword#g"
done < replace.txt

Open in new window


For this to work, replace.txt has to be in the same directory as the script.  You should also replace /var/tmp/test with the directory which holds the files you want to change.

NOTE: You can remove the "echo" lines if you wish, I did that just for testing.

Author

Commented:
Do you mind to put comment in each line so that I can follow your logical ?

Thank again.
#!/bin/bash
# Read replace.txt line by line
while read line; do
        # Take first word of line and make it a variable - word to find
        word=`echo $line | awk '{print $1}'`
         # Take second work of line and make it a variable - replace first word with this word
        newword=`echo $line | awk '{print $2}'`

echo "WORD is $word"
echo "Replace WORD with $newword"

# Find every file in /var/tmp/test then swap first word for second word
find /var/tmp/test -type f | xargs sed -i "s#$word#$newword#g"
#done
done < replace.txt

Author

Commented:
Tks

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial