我试图使用查找-exec与多个命令没有任何成功。有人知道像下面这样的命令是否可行吗?

find *.txt -exec echo "$(tail -1 '{}'),$(ls '{}')" \;

基本上,我试图打印当前目录中每个txt文件的最后一行,并打印在行末,逗号后跟文件名。


当前回答

应该使用xargs:)

find *.txt -type f -exec tail -1 {} \; | xargs -ICONSTANT echo $(pwd),CONSTANT

另一个(在osx上工作)

find *.txt -type f -exec echo ,$(PWD) {} + -exec tail -1 {} + | tr ' ' '/'

其他回答

find . -type d -exec sh -c "echo -n {}; echo -n ' x '; echo {}" \;

有一个更简单的方法:

find ... | while read -r file; do
    echo "look at my $file, my $file is amazing";
done

另外:

while read -r file; do
    echo "look at my $file, my $file is amazing";
done <<< "$(find ...)"

我不知道你是否可以用find来做这个,但是另一个解决方案是创建一个shell脚本并用find来运行这个。

lastline.sh:

echo $(tail -1 $1),$1

使脚本可执行

chmod +x lastline.sh

使用找到:

find . -name "*.txt" -exec ./lastline.sh {} \;

我通常将find嵌入到一个小的for循环一行中,其中find在带有$()的子命令中执行。

你的命令看起来像这样:

for f in $(find *.txt); do echo "$(tail -1 $f), $(ls $f)"; done

好的一点是,你不用{}只用$f,不用-exec…你把所有的命令都写在do和;完成了。

不知道你到底想做什么,但也许像这样?

for f in $(find *.txt); do echo $f; tail -1 $f; ls -l $f; echo; done

感谢Camilo Martin,我得以回答一个相关的问题:

我想做的是

find ... -exec zcat {} | wc -l \;

但这并不奏效。然而,

find ... | while read -r file; do echo "$file: `zcat $file | wc -l`"; done

确实有用,所以谢谢!