如何在查找表达式中使用带有 sed 的文件名 [英] How to use the name of the file with sed in a find expression
问题描述
尝试回答使用 Bash/Perl 根据每个文件的名称修改文件不知道如何一起使用 find
和 sed
.
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.
如果它是一个普通的 for
循环,我们会这样做:
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
但是假设我们要使用 find
来更改所有子目录中的文件.在这种情况下,我会使用...
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
但是sed
中的这些{}
不被接受,我收到错误
but these {}
within sed
are not accepted and I get the error
sed:-e 表达式 #1,字符 20:`s' 的未知选项
sed: -e expression #1, char 20: unknown option to `s'
我发现了一些类似的问题(1)但无法概括到足以让我在这种情况下可以理解.
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!
推荐答案
find
将根据您指定的路径返回 pathnames(相对或绝对).
find
would return pathnames (relative or absolute) depending upon the path you specify.
这会与您指定的分隔符冲突,即 /
.更改 sed
的分隔符,你应该很好:
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" {} ;
要从路径中删除前导 ./
,您可以尝试:
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 ...
这篇关于如何在查找表达式中使用带有 sed 的文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!