0

I am trying to use sed to find files with certain extension and then replace occurrences of a certain string with another.

No directory mentioned using current directory
*.h
sed: can't read *.h: No such file or directory
*.C
sed: can't read *.C: No such file or directory
*.cc
sed: can't read *.cc: No such file or directory
un.cpp

This is the code in my script:

for file in *.{h,C,cc,cpp}
       do
          echo $file;
          sed -i -e 's/${1}/${2}/g' $file;
       done

I am having a similar issue when I am trying to use sed on sub folders recursively using find:

find ./*.{h,C,cc,cpp} -type f -exec sed -i -e 's/${2}/${3}/g' {} \;

Thank you

0
3

find . -type f -a \( -name "*.h" -o -name "*.C" -o -name "*.cc" -o -name "*.cpp" \) -a -exec sed -i -e "s/${2}/${3}/g" {} +

Should work.

In your first script the problem was that if there is no match for e.g. *.h, bash will pass the literal *.h to sed, which will then think it's a filename, but since no such file exists, it'll fail.

In the 2nd case, with find(1), you were having the shell look for matching filenames in the current directory and then pass them to find(1).

In the sed statement you need double quotes instead of single quotes for the shell to perform variable expansion within the quoted string.

4
  • I created a file called test.cpp in my current directory and ran the script with the command you mentioned: ` find . -type f -a ( -name ".h" -o -name ".C" -o -name ".cc" -o -name ".cpp" ) -a -exec sed -i -e 's/${1}/${2}/g' {} + ` . I ran the script like change "bad" "good" but nothing happened (name of script is change)
    – KLMM
    Jan 20 '16 at 23:05
  • also tried directly executing this command: find . -type f -a ( -name ".h" -o -name ".C" -o -name ".cc" -o -name ".cpp" ) -a -exec sed -i -e 's/"bad"/"good"/g' {} +. Didn't work, the file wasn't overwritten
    – KLMM
    Jan 20 '16 at 23:18
  • realized that i needed to use " instead of ' in the sed command. Thank you for the help
    – KLMM
    Jan 21 '16 at 14:32
  • Ah, right, I missed that, sorry. Jan 21 '16 at 17:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.