使用以下内容,我将文件名添加到每一行的前面,并将输出发送到单个文件。
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: Only one instance of {} is supported with -exec ... +
输入文件是这样的——
文件A.txt
A1
A2
文件B.txt
B1
B2
期望的输出
fileA.txt A1
fileA.txt A2
fileB.txt B1
fileB.txt B2
我知道如何用 awk 做到这一点,但我想用 sed、find 和 exec 或 xargs 来做到这一点。
最佳答案
find . -type f |xargs awk '$0=FILENAME$0' > out
当我回答这个问题时,您的“no awk”行还没有出现。无论如何,看看下面我更新的答案:
根据评论更新
所以你想使用 find、exec/xargs 和 sed 来做这件事。我的脚本需要 GNU Sed ,我希望你拥有它。
先看一行:(好吧,
> out
被省略了。你可以把它加到行尾。)find . -type f | xargs -i echo {}|sed -r 's#(.\/)(.*)#cat &\|sed "s:^:file \2 :g"#ge'
现在让我们来测试一下,见下图:
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
结果是你的期望吗?
简短说明
find ....|xargs -i echo {}
无需解释,只需打印每行文件名(带前导
"./"
)sed -r 's#(.\/)(.*)# MAGIC
#ge'
这样的 sed 行\1: "./"
和\2 "a.txt"(filename)
e
在 sed 行的末尾,魔法部分将是作为 shell 命令执行。(需要 GNU sed)
cat &\|sed "s:^:file \2 :g
cat & 只是输出文件内容,并通过管道传输到另一个 sed。进行替换 (
s:..:..:g
) 外部 sed。
关键是 Gnu sed 的“e”。
关于shell - 使用 find 和 sed 将文件名添加到文件开头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7812497/