Find and replace a word in all the files (that contain the word) under a directory

Hi Everyone,

I am looking for a simple way for replacing all the files under a directory that use the server "xsgd1234dap" with "xsdr3423pap".

For Example:

In the Directory,

[xgdfy3487]$pwd
/home/nick

[xgdfy3487] $ grep -l "xsgd1234dap" *.sh | wc -l
119

I have "119" files that are still using "xsgd1234dap" but Instead I would like replace it with "xsdr3423pap" for all the files (119).

Could someone please tell me any easier way to do this instead of manually doing it file by file.

I would really appreciate you time and thoughts.

Make a backup first

Then:

find . -name "*sh" |xargs perl -pi -e 's/find/replace/g'

it was tested on solaris

1 Like

-i.bak will do the backup.

grep -l "xsgd1234dap" *.sh  |xargs perl -i.bak -pe 's/xsgd1234dap/xsdr3423pap/g' 
1 Like

Thanks a lot for your replies.

Really solved my problem.

Appreciate your thoughts. :b:

 
grep -l "xsgd1234dap" *.sh | while read filename
do
     cp $filename $filename.bk
     sed -i 's/xsgd1234dap/xsdr3423pap/g' $filename
done

No backups. No reading the same file twice. No remorse. Just ed. :slight_smile:

for f in *.sh; do
    ed -s "$f" <<-'EOED'
        1,$s/xsgd1234dap/xsdr3423pap/g
        w
        q
    EOED
done

Note: The heredoc indentation must consist of tabs (not spaces).

Alternatively:

for f in *.sh; do
    printf %s\\n '1,$s/xsgd1234dap/xsdr3423pap/g' w q | ed -s "$f"
done

Regards,
Alister