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

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

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


当前回答

下列其中一项:

find *.txt -exec awk 'END {print $0 "," FILENAME}' {} \;

find *.txt -exec sh -c 'echo "$(tail -n 1 "$1"),$1"' _ {} \;

find *.txt -exec sh -c 'echo "$(sed -n "\$p" "$1"),$1"' _ {} \;

其他回答

另一种方法是这样的:

multiple_cmd() { 
    tail -n1 $1; 
    ls $1 
}; 
export -f multiple_cmd; 
find *.txt -exec bash -c 'multiple_cmd "$0"' {} \;

在一行中

multiple_cmd() { tail -1 $1; ls $1 }; export -f multiple_cmd; find *.txt -exec bash -c 'multiple_cmd "$0"' {} \;

“multiple_cmd()”-是一个函数 "export -f multiple_cmd" -将导出它,以便任何其他subshell都可以看到它 “找到* . txt - bash - c”multiple_cmd“0”{}\;”-找到将在你的例子中执行函数

通过这种方式,multiple_cmd可以根据您的需要任意长和复杂。

希望这能有所帮助。

Find命令接受多个-exec部分。例如:

find . -name "*.txt" -exec echo {} \; -exec grep banana {} \;

注意,在这种情况下,只有当第一个命令成功返回时,第二个命令才会运行,正如@Caleb提到的那样。如果你想让两个命令都运行,不管它们成功或失败,你可以使用这个结构:

find . -name "*.txt" \( -exec echo {} \; -o -exec true \; \) -exec grep banana {} \;

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

我想做的是

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

但这并不奏效。然而,

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

确实有用,所以谢谢!

扩展@Tinker的回答,

在我的例子中,我需要在-exec中创建一个命令|命令|命令来打印文件名和在包含特定文本的文件中找到的文本。

我可以用:

find . -name config -type f \( -exec  grep "bitbucket" {} \; -a -exec echo {} \;  \) 

结果是:

    url = git@bitbucket.org:a/a.git
./a/.git/config
    url = git@bitbucket.org:b/b.git
./b/.git/config
    url = git@bitbucket.org:c/c.git
./c/.git/config

下列其中一项:

find *.txt -exec awk 'END {print $0 "," FILENAME}' {} \;

find *.txt -exec sh -c 'echo "$(tail -n 1 "$1"),$1"' _ {} \;

find *.txt -exec sh -c 'echo "$(sed -n "\$p" "$1"),$1"' _ {} \;