Categories

Our Sponsors

Command Line Search and Replace

So you want to change some text in many unix files.

Try the following.

perl -pi -e ’s/find/replace/g’ *.txt

or to script it out.
Find the TEXT in regular files and replace with NEWTEXT

for file in `find ./ -type f -exec grep -l TEXT {} \;`
do
perl -pi -e ’s/TEXT/NEWTEXT/g’ $file
done

I found out how to pass KSH variables to awk, just in case this ever comes in handy.

VAR=”some_data”

echo “This is nice” | awk ‘{ print $1, avar, $2, $3 }’ avar=$VAR

> This some_data is nice

Or a better example; Changing file names.

VAR=”.poop”
for x in *.php
do
echo “moving $x to \c” ;echo $x | awk -F. ‘{ print $1 newext }’ newext=$VAR
mv $x `echo $x | awk -F. ‘{ print $1 newext }’ newext=$VAR’`
done

> moving test1.php to test1.poop
> moving test2.php to test2.poop
> moving test3.php to test3.poop

Of course if you had a file called test.this.file.php the awk statement above would mv it to test.poop and drop the other items after the first period.  There is probably a nice way to code around this, but hey, this works. for now.

  • Share/Bookmark

Leave a Reply

 

 

 

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Get Adobe Flash playerPlugin by wpburn.com wordpress themes