Shell 使用find和sed将文件名添加到文件开头

Shell 使用find和sed将文件名添加到文件开头,shell,sed,find,Shell,Sed,Find,使用以下命令,我将文件名添加到每行的前面,并将输出发送到单个文件 ls | while read file; do sed -e "s/^/$file/g" $file > out; done 我想执行相同的sed替换,但使用find和exec或xargs命令- find . -type f -exec sed "s/^/{}/g" {} > out + 但我有一个错误- find:只有一个{}实例受-exec+ 输入文件如下- fileA.txt A1 A2 fileB.tx

使用以下命令,我将文件名添加到每行的前面,并将输出发送到单个文件

ls | while read file; do sed -e "s/^/$file/g" $file > out; done
我想执行相同的
sed
替换,但使用
find
exec
xargs
命令-

find . -type f -exec sed "s/^/{}/g" {} > out +
但我有一个错误-

find:只有一个{}实例受-exec+

输入文件如下-

fileA.txt

A1
A2
fileB.txt

B1
B2
期望输出

fileA.txt A1
fileA.txt A2
fileB.txt B1
fileB.txt B2

我知道如何使用awk实现这一点,但我希望使用sed、find and exec或xargs实现。未经测试,请尝试使用xargs

find . -type f | xargs -I FILE sed "s/^/FILE/g" FILE > out
那么:

find . -type f | xargs -i echo FILE/{} > out

为什么不简单地将第一行中的
ls
替换为
find
,如下所示

find . -type f | while read file; do sed -e "s|^|$file|" $file > out; done
您只能将
/
中的
s
分隔符交换到文件名中不包含的其他内容。我选择了
|
作为例子

 find . -type f |xargs awk '$0=FILENAME$0' > out
当我回答这个问题时,你的“no awk”行还没有出现。无论如何,请看下面我更新的答案:

根据评论更新

因此,您需要使用find、exec/xargs和sed来完成这项工作。我的脚本需要GNU-Sed,我希望你有它

先看一行:(嗯,
>out
被省略了。您可以将它添加到行的末尾。)

现在让我们做一个测试,见下面:

kent$  head *.txt
==> a.txt <==
A1
A2

==> b.txt <==
B1
B2

kent$  find . -type f | xargs -i echo {}|sed -r 's#(.\/)(.*)#cat &\|sed  "s:^:file \2 :g"#ge'
file b.txt B1
file b.txt B2
file a.txt A1
file a.txt A2
kent$head*.txt

==>a.txt b.txt这个对我来说很好用,而且比Kent的答案更简单
注意:然后插入该路径的完整路径名

find . -type f | xargs -r -t -i sed -r 's|^|'{}' |g' {}
使用此选项仅保留裸文件名部分

find . -type f | xargs -r -t -i sed -r -e 's|^|'{}' |g' -e 's|^.+/||g' {}
然后,如果您对标准输出结果满意,您可以添加-i切换到sed命令以覆盖文件

find . -type f | xargs -r -t -i sed -i -r -e 's|^|'{}' |g' -e 's|^.+/||g' {}

你能修改你的问题,举例说明你想要什么样的产出吗?我不太了解它目前的编写情况。从我所看到的情况来看,使用-exec要快得多,而且我有成千上万的文件。@Bryan:到目前为止还没有提到性能。由于
find-exec
while
循环都将为每个文件创建一个新的
sed
过程,因此您既不会得到什么,也不会失去什么。进一步:我预计,大部分时间将用于阅读和编写文件的内容。仅供参考,对于少量文件-查找时间-类型f-exec sed“s/^/replacement/g”{}+需要实际的0m0.736s,但需要时间查找-读取文件时键入f |;do sed-e“s | ^ | replacement |”$文件;完成需要真正的0m3.165s。使用xargs而不是exec只是一点点faster@Bryan:对于持续的
替换
您是对的。但这不是问题中的问题。问题是需要变量替换-每个文件都有变量。因此,每个文件需要一个
sed
调用。因此,您既不能使用
find | xargs
也不能使用
find-exec+
。正如我在问题中所说,我知道如何使用awk实现这一点,但我希望使用sed和find。谢谢,如果您有时间和兴趣,您能添加一些解释性意见吗?答案中添加了解释。@布赖恩:我很好奇:这个解决方案在您的数据上的性能如何?非常慢。我的awk解决方案就是我正在使用的。将“/”改为“|”对我很有效<代码>查找-键入f | xargs-I FILE sed“s | | FILE | g”FILE>out
find . -type f | xargs -r -t -i sed -i -r -e 's|^|'{}' |g' -e 's|^.+/||g' {}