Grace Huang
Grace Huang

Reputation: 5679

How to turn this command into a zsh function

This is the command I want to translate into a zsh function, which does a global search and replace for a string:

find ./ -type f -exec sed -i 's/string1/string2/' {} \;

I tried:

gr () {
    find ./ -type f -exec sed -i 's/$1/$2/' {} \;
}

But it does not seem to work.

Upvotes: 0

Views: 259

Answers (1)

mpy
mpy

Reputation: 171

The obvious error is the wrong quoting -- as always. ' prevents the shell to expand the variables, which is what you want. Use " instead -- and probably you also want the global flag for sed:

gr () {
    find ./ -type f -exec sed -i "s/$1/$2/g" {} \;
}

However, this is not very zsh-stylish... the following is shorter and IMHO better to read:

gr () {
    sed -i "s/$1/$2/g" **/*(.)
}
  • ** searches recursively, but does not follow symlinks (use *** if you want that)
  • (.) limits the results to plain files

Upvotes: 4

Related Questions