1832750 Members
3357 Online
110045 Solutions
New Discussion

Search and replace

 
SOLVED
Go to solution
Shivkumar
Super Advisor

Search and replace

Hi,

How to search and replace a particuler word in all the files starting from a particular directory /opt/usr ?

Thanks,
Shiv
4 REPLIES 4
James R. Ferguson
Acclaimed Contributor
Solution

Re: Search and replace

Hi SHiv:

Simply:

# cd /path && find . -type f -exec perl -pi -e 's/\bworld\b/shiv/' \+

This would find only *files* in '/path' containing the string "world" and replace it with "shiv". Only strings bounded by non-word characters (e.g. whitespace) are matched and substituted. Hence, "hello world" becomes "hello shiv" but "hello worldly" remains unaltered.

If you want to preseve a copy of any files before modification, do:

# # cd /path && find . -type f -exec perl -pi.old -e 's/\bworld\b/shiv/' \+

...the backup copy of each file will be named with the suffix ".old".

Regards!

...JRF...

Luis Cardenas Perez
Valued Contributor

Re: Search and replace

If you need to change the name I would do this:
create a script with instruction:
mv $1 `echo $1 | sed s/veinte/treinta/`

and Execute:

find /directory -name *expression* -exec script \{\} \;
Bill Hassell
Honored Contributor

Re: Search and replace

Here's a script that will do exactly what you want with extras. It can be used with STDIN or one or more files. The default mode (no options) is to preview the lines that will be affected with a before and after list. To make the preview permanent, add the -w to write the changes. If you want to suppress the before/after lines, add the -q option and to remove the title and summary lines, use -s (for silent). Examples:

echo "line 1\nline 2" | chgafile -ws line Line
Line 1
Line 2

chgafile debug "--> DEBUG <--" myfile
(previews the changed lines, leaves myfile unchanged)

chgafile -w debug "--> DEBUG <--" myfile

Previews the changes and also writes the changes to myfile.


Bill Hassell, sysadmin
Arturo Galbiati
Esteemed Contributor

Re: Search and replace

Hi,
I use this script (no perl used) to change files

HTH,
Art