问题
Trying to answer Using Bash/Perl to modify files based on each file's name I ended in a point in which I don't know how to use find
and sed
all together.
Let's say there is a certain structure of files in which we want to change a line, appending the name of the file.
If it was a normal for
loop we would do:
for file in dir/*
do
sed -i "s/text/text plus $file/g" $file
done
But let's say we want to use find
to change files from all subdirectories. In this case, I would use...
find . -type f -exec sed -i "s/text/text plus {}/g" {} \;
^
it does not like this part
but these {}
within sed
are not accepted and I get the error
sed: -e expression #1, char 20: unknown option to `s'
I found some similar questions (1) but could not generalize it enough to make it understandable for me in this case.
I am sure you guys will come with a great solution for this. Thanks!
回答1:
find
would return pathnames (relative or absolute) depending upon the path you specify.
This would conflict with the delimiter you've specified, i.e. /
. Change the delimiter for sed
and you should be good:
find . -type f -exec sed -i "s|text|text plus {}|g" {} \;
EDIT: For removing the leading ./
from the paths, you can try:
find . -type f -exec sh -c '$f={}; f=${f/.\//}; sed -i "s|text|text plus ${f}|g" {}' \;
I'm certain that better solutions might exist ...
回答2:
I really think the issue is that your files name contains a /
that is why sed believes it start the options strings.
Replace /
by @
in you sed command would do the job.
I try that on Linux BASH and it work perfectly
find . -type f -exec sed -i -e "s@text@test plus {}@g" {} \;
来源:https://stackoverflow.com/questions/17788947/how-to-use-the-name-of-the-file-with-sed-in-a-find-expression