Operating System - HP-UX
1834459 Members
2565 Online
110067 Solutions
New Discussion

replacing a value of the same variable in multiple files

 
SOLVED
Go to solution
Hanry Zhou
Super Advisor

replacing a value of the same variable in multiple files

I need to replace a value which is assinged to the same variable "XYZ" in multiple of files, how do i achieve that by ksh? Thanks,

file
....
XYZ=val
...


none
5 REPLIES 5
Paul Sperry
Honored Contributor
Solution

Re: replacing a value of the same variable in multiple files

A script like this should do the trick
Just create it make it executable and run it

#!/usr/bin/ksh
find . -depth -exec grep -l 'XYZ'{} \; | while read x
do
sed "s/XYZ/ABC/g" < ${x} > ${x}.tmp
mv ${x}.tmp $x
done
A. Clay Stephenson
Acclaimed Contributor

Re: replacing a value of the same variable in multiple files

#!/usr/bin/sh
TDIR=${TMPDIR:-/var/tmp}
T1=${TDIR}/X${$}_1.tmp

while [[ ${#} -ge 1 ]]
do
FNAME=${1}
shift
if [[ -w "${FNAME}" && -f "${FNAME}" ]]
then
sed s/XYZ=val/XYZ=newval/ < ${FNAME} > ${T1}
mv ${T1} ${FNAME}
fi
done

Use it like this:
fix.sh file1 file2 ...

If it ain't broke, I can fix that.
Rodney Hills
Honored Contributor

Re: replacing a value of the same variable in multiple files

Perl can do it in one line-

perl -pi -e 's/XYZ=val/XYZ=new/g' *.c

This will replace the text in all files that end with ".c".

HTH

-- Rod Hills

There be dragons...
Hanry Zhou
Super Advisor

Re: replacing a value of the same variable in multiple files

I want to replace /d1/d2/d3/d4 with /r1/r2/r4/r5, a lot of "/"'s, how do I do that using sed?

I used "\" in front of every "/", but got eorror "cannot be parsed"?

thanks,
none
Charlie Rubeor
Frequent Advisor

Re: replacing a value of the same variable in multiple files

Try:

sed "s|/d1/d2/d3/d4|/r1/r2/r3/r4|g" file.

Notice the double quotes and the pipe.