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
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.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments