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🙂

6 comentarios en “using sed to replace a string in files recursively

  1. 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! :¬)

  2. 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”

  3. 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 cnd e f”
    a b c
    d e f
    tripu@astroboy:/tmp$ for i in `echo -e “a b cnd e f”`; do echo $i; done
    a
    b
    c
    d
    e
    f

    But:

    tripu@astroboy:/tmp$ echo -e “a b cnd e f” | (while read a; do echo $a; done)
    a b c
    d e f

    (Cheers, Artu — your post was very useful to me ;¬)

  4. 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!

Responder

Introduce tus datos o haz clic en un icono para iniciar sesión:

Logo de WordPress.com

Estás comentando usando tu cuenta de WordPress.com. Cerrar sesión / Cambiar )

Imagen de Twitter

Estás comentando usando tu cuenta de Twitter. Cerrar sesión / Cambiar )

Foto de Facebook

Estás comentando usando tu cuenta de Facebook. Cerrar sesión / Cambiar )

Google+ photo

Estás comentando usando tu cuenta de Google+. Cerrar sesión / Cambiar )

Conectando a %s