简体   繁体   English

如何在查找表达式中使用带有sed的文件名

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

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. 尝试回答使用Bash / Perl根据每个文件的名称修改文件我结束了一点,我不知道如何使用findsed all。

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我们会这样做:

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. 但是,假设我们想使用find来更改所有子目录中的文件。 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中的这些{}不被接受,我得到了错误

sed: -e expression #1, char 20: unknown option to `s' sed:-e expression#1,char 20:`s'的未知选项

I found some similar questions ( 1 ) but could not generalize it enough to make it understandable for me in this case. 我发现了一些类似的问题( 1 ),但在这种情况下,我无法将其概括为足以让我理解。

I am sure you guys will come with a great solution for this. 我相信你们会为此提供一个很好的解决方案。 Thanks! 谢谢!

I really think the issue is that your files name contains a / that is why sed believes it start the options strings. 我真的认为问题是你的文件名包含/这就是为什么sed认为它启动选项字符串。

Replace / by @ in you sed command would do the job. 在你的sed命令中替换/ by @将完成这项工作。

I try that on Linux BASH and it work perfectly 我尝试在Linux BASH上运行,它完美无缺

find . -type f -exec sed -i -e "s@text@test plus {}@g" {} \;

find would return pathnames (relative or absolute) depending upon the path you specify. find将返回路径名 (相对或绝对),具体取决于您指定的路径。

This would conflict with the delimiter you've specified, ie / . 这会与您指定的分隔符冲突,即/ Change the delimiter for sed and you should be good: 更改sed的分隔符,你应该是好的:

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 ... 我确信可能存在更好的解决方案......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM