Link to home
Start Free TrialLog in
Avatar of AXISHK
AXISHK

asked on

bash script to change texts in a list of files

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
Avatar of Steven Vona
Steven Vona
Flag of United States of America image

#!/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.
Avatar of AXISHK
AXISHK

ASKER

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

Thank again.
ASKER CERTIFIED SOLUTION
Avatar of Steven Vona
Steven Vona
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of AXISHK

ASKER

Tks