0

there, In my bash script, I define a command line function:

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

After source ~/.bashrc
when I type: rep get foo It doesn't work. Does anyone know what's going on here?

1
  • "It doesn't work" is very unspecific. Until I read the answer I thought your code failed to define the function somehow. My bad for being on the wrong track, but as the instructions in the help section amplify many times over, you want to be as specific as possible next time. Commented Jun 26, 2015 at 3:41

1 Answer 1

4

Single quotes around the sed 's/$1/$2/g' prevent bash from evaluating the $1 and $2 function arguments into strings - your command right now will swap a file with $1 in it for $2.

Try using double quotes instead.

rep() {
 find . -type f -exec sed -i -e "s/$1/$2/g" {} \;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Actually, the OP's attempt would not swap literal $1 because $ in a regex represents the end of line. There can obviously not be anything after end of line, so $1 would never match anything; and so the OP's script would do nothing at all (except needlessly copy the file over itself).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.