Thomas Phan Thomas Phan - 1 year ago 71
Linux Question

sed is working for a hard-coded file name but not for variable containing said file name

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:

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.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download