1830241 Members
1404 Online
109999 Solutions
New Discussion

Scripting Help

 
SOLVED
Go to solution
George Chechakunnil
Frequent Advisor

Scripting Help

Hello Gurus,

I need to grep for a specific pattern in all the files in a directory and change them to a new pattern.

I tried with sed.

for i in
do
sed 's/old/new $i > /newdirectory/$i
done

it works but the problem is that the files are being truncated when piping to the new file

is there a way i can change the pattern in the same file itself?

thanks in advance
I am like a small boy picking up pebbles in god's vast shore of knowledge --- Sir Issac Newton
7 REPLIES 7
Dennis Handly
Acclaimed Contributor
Solution

Re: Scripting Help

Your sed solution should work. You forgot a single quote:
sed 's/old/new/' $i > /newdirectory/$i

You aren't piping but redirecting. What was the truncation like?? Number of lines or width of them? Long long are they??

Changing a pattern the file can be done with perl, search some previous thread.

Some of them show using ex(1) and ed(1) to do this.
Yogeeraj_1
Honored Contributor

Re: Scripting Help

hi,

i have some scripts which does it as follows:

e.g.

for file in `find . -name "*.htm"`
do
echo "Converting $file ..."
cat $file | sed s/$1/$2/g> /tmp/newfile
cp /tmp/newfile $file
done


hope this helps too!

kind regards
yogeeraj
No person was ever honoured for what he received. Honour has been the reward for what he gave (clavin coolidge)
john korterman
Honored Contributor

Re: Scripting Help

Hi,

you should perhaps add "g" to your sed statement, e.g.:

sed 's/old/new/g' $i > /tmp/$i

else you will only have the first occurrance replaced.

regards,
John K.


it would be nice if you always got a second chance
Yogeeraj_1
Honored Contributor

Re: Scripting Help

hi again,

another way to do it would be using PERL:

perl -pi -e 's/old/new/g' $file

you can replace the sed command in the previous script with this...

hope this helps too!

kind regards
yogeeraj
No person was ever honoured for what he received. Honour has been the reward for what he gave (clavin coolidge)
Dennis Handly
Acclaimed Contributor

Re: Scripting Help

rmueller58
Valued Contributor

Re: Scripting Help

I use perl unless I need to retain a copy of the original file.

if you intend to change occurances in multiple files within a directory I'd create a for loop, otherwise simply use a perl command.

MULTIFILES

for fn in `ls`
do
perl -pi -e s/old/new/g $fn
done

Single files
perl -pi -e s/old/new/g filename

Arturo Galbiati
Esteemed Contributor

Re: Scripting Help

Hi,
only a sugegstion:

for i in $(grep old *)
do
sed 's/old/new' $i > /newdirectory/$i
done

This will increase teh speed in cas eyou have a lot of files in your dir, and yoy could also refine you grep to get only ascii file, etc.

HTH,
Art