1

Sorry if this turns out to be a dumb question, but I'm just lost on what could be wrong with my sed command.

This is the entire commands that I have:

file="hello_world.cpp"
grep -lrI "$file" dir/ | xargs sed -i 's/\(\$file\)/\1\.bin/'

Basically I am searching for any file that contains the string "hello_world.cpp", then passing them into sed to append the extension .bin to the string (Yes that might not make sense, but I'm just using a generic example. I do need this specific functionality for what I'm working on).

The problem I'm having is that while the grep and string assignment works as expected, the sed command isn't. What confuses me even more is that this following command works.

grep -lrI "$file" dir/ | xargs sed -i 's/\(hello_world.cpp\)/\1\.bin/'

This replaces the string "hello_world.cpp" with "hello_world.cpp.bin" inside all the files that contain the string "hello_world.cpp", which is exactly how I want it to be.

If anyone could help point out my mistake, it'd be greatly appreciated. Thanks.

Thomas Phan
  • 249
  • 2
  • 17
  • 1
    Use double quotes instead of single quotes in sed while using shell variables – anubhava Jul 20 '16 at 22:34
  • 1
    Damn it, I knew it was something simple. Thank you. Would you mind moving your comment to the answer section so I could mark it as an answer? – Thomas Phan Jul 20 '16 at 22:41

1 Answers1

1

Problem is here:

xargs sed -i 's/\(\$file\)/\1\.bin/'

Since you're using shell variable inside single quotes where it doesn't get expanded.

You can use double quotes to expand it:

xargs sed -i "s/$file/&.bin/"

Also note that there is no need to use capture group as you can use & in replacement.

anubhava
  • 761,203
  • 64
  • 569
  • 643