using sed to replace a string in files recursively
for i in `grep -iR ‘\/usr\/bin\/perl’ * | cut -f 1 -d ‘:’ | sed ’s/.*/”&”/’`; do sed ’s/\/usr\/bin\/perl/\/opt\/lampp\/bin\/perl/g’ $i > /tmp/TMPFILE && mv /tmp/TMPFILE $i ; done
Update: the bold text expression wraps with double quotes the filenames, so the problem with spaces in filenames should dissapear. Thanks Tripu


I’ve had issues a couple of times in the past when filenames returned by «grep» contain spaces — in such case those files are split up and treated by «for» as if they were different files.
I solved that after some struggling, but because I wasn’t as disciplined as you and didn’t wrote that down in my blog, now I can’t remember the solution :¬( I remember that it was not as easy as simply using «xargs» or escaping spaces with backslashes.
Do you know how to «protect» your one-liner against spaces in filenames? (Don’t waste time on this if you don’t — it’s just that I want to nail it down once and forever! :¬)
tripu
Abril 2, 2009 a 6:13 pm
I think it is already fixed. Thanks!
arturogf
Abril 3, 2009 a 8:22 am
Mmmh… I think that does not work. “for i in…” splits on spaces even if there are double quotes:
tripu@astroboy:/tmp$ echo \”a b c\”
“a b c”
tripu@astroboy:/tmp$ for i in `echo \”a b c\”`; do echo $i; done
“a
b
c”
tripu
Abril 3, 2009 a 8:50 pm
Argh! How can I be so silly? I forgot that actually I *had* blogged about it:
http://blog.tripu.info/item/loc
Try replacing your “for i in” loop with a “while read a”. So, following the example in my previous comment:
tripu@astroboy:/tmp$ echo -e “a b c\nd e f”
a b c
d e f
tripu@astroboy:/tmp$ for i in `echo -e “a b c\nd e f”`; do echo $i; done
a
b
c
d
e
f
But:
tripu@astroboy:/tmp$ echo -e “a b c\nd e f” | (while read a; do echo $a; done)
a b c
d e f
(Cheers, Artu — your post was very useful to me ;¬)
tripu
Abril 3, 2009 a 11:18 pm
Uhm, ok, … I’ll write the sentence “don’t skip the unit testing” 100 times on the blackboard hehe
.
Strange behaviour has the “for” loop, even if you quote blank spaces with ‘\’, it does not run as it should.
Thanks twice!
arturogf
Abril 5, 2009 a 8:33 pm