How to use the name of the file with sed in a find expression

时光毁灭记忆、已成空白 提交于 2020-01-10 05:25:07

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!