Page 1 of 1

replacing text by unix shell?

Posted: Tue Jul 04, 2006 9:37 pm
by eugene2008
Good day, *nix gurus!
I have a file named functions.php, its located in many folder with different names under /home/site/ directory
functions.php has this string:
$arr[$i]=($i==$page) ? "<font color=red>[$k]</font>" : "<a href=page_$i.html>[$k]</a>";
I want to replace this string to:
$arr[$i]=($i==$page) ? "<font color=red size=1>[$k]</font>" : "<font size=1><a href=page_$i.html>[$k]</a></font>";
how do i do that in shell?

replacing text by unix shell?

Posted: Wed Sep 20, 2006 6:08 am
by ibbo
This may look like complete garbage to you but I assure you it does exaclty what your after. It will also do it for every matching file in that directory and its sub directories.

The reson it looks so messy is because of your rather large string (and the fact that I had to escape much of it).

Working example

Code: Select all

perl -p -i -e 's/\$arr\[\$i\]=\(\$i==\$page\) \? \"<font color=red>\[\$k\]<\/font>\" \: \"<a href=page_\$i\.html>\[\$k\]<\/a>\"\;/\$arr\[\$i\]=\(\$i==\$page\) \? \"<font color=red size=1>\[\$k\]<\/font>\" \: \"<font size=1><a href=page_\$i\.html>\[\$k\]<\/a><\/font>\"\;/g' `grep -rI  color=red * | awk -F : '{print $1}' | sort | uniq | xargs`
To get your head around it I'll show you a rather simplified one.

Create a file or many files and put boo.htm inside it.

You now realise that boo.htm should be boo.html

so

Code: Select all

perl -p -i -e 's/boo\.htm/boo\.html/g'  `grep -rI boo.htm * | awk -F : '{ print $1 }' | sort | uniq | xargs`

Code: Select all

perl -p -i -e 's/boo\.htm/boo\.html/g'
Invokes perl from the shell and does a pattern match and repalce.

Code: Select all

`grep -rI boo.htm * | awk -F : '{ print $1 }' | sort | uniq | xargs`
This part is the bit that actually finds all files with boo.htm inside them and feeds them into the perl part above. sort xargs etc are simply ordering the input of the files to be parsed via the perl one liner.

Job done.

P.S this is by no means a complete explanation of how this works, if you require one I can provide but as its dinner time now is not the time :)

Hope that helped, I use it often.

Ibbo