我试图使用查找-exec与多个命令没有任何成功。有人知道像下面这样的命令是否可行吗?
find *.txt -exec echo "$(tail -1 '{}'),$(ls '{}')" \;
基本上,我试图打印当前目录中每个txt文件的最后一行,并打印在行末,逗号后跟文件名。
我试图使用查找-exec与多个命令没有任何成功。有人知道像下面这样的命令是否可行吗?
find *.txt -exec echo "$(tail -1 '{}'),$(ls '{}')" \;
基本上,我试图打印当前目录中每个txt文件的最后一行,并打印在行末,逗号后跟文件名。
当前回答
我不知道你是否可以用find来做这个,但是另一个解决方案是创建一个shell脚本并用find来运行这个。
lastline.sh:
echo $(tail -1 $1),$1
使脚本可执行
chmod +x lastline.sh
使用找到:
find . -name "*.txt" -exec ./lastline.sh {} \;
其他回答
我找到了这个解决方案(可能已经在评论中说过了,但我找不到任何答案)
你可以使用bash -c在一行中执行多个命令
find . <SOMETHING> -exec bash -c "EXECUTE 1 && EXECUTE 2 ; EXECUTE 3" \;
在你的情况下
find . -name "*.txt" -exec bash -c "tail -1 '{}' && ls '{}'" \;
我用一个测试文件测试了它:
[gek@tuffoserver tmp]$ ls *.txt
casualfile.txt
[gek@tuffoserver tmp]$ find . -name "*.txt" -exec bash -c "tail -1 '{}' && ls '{}'" \;
testonline1=some TEXT
./casualfile.txt
另一种方法是这样的:
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+xargs的答案。
下面的例子找到所有的.html文件,并创建一个附加了. bak扩展名的副本(例如1.html > .html. bak)。
带有多个占位符的单个命令
find . -iname "*.html" -print0 | xargs -0 -I {} cp -- "{}" "{}.BAK"
具有多个占位符的多个命令
find . -iname "*.html" -print0 | xargs -0 -I {} echo "cp -- {} {}.BAK ; echo {} >> /tmp/log.txt" | sh
# if you need to do anything bash-specific then pipe to bash instead of sh
这个命令也适用于以连字符开头或包含空格的文件,例如-my file.html,这要感谢参数引用和cp后面的——它向cp发出参数结束和实际文件名开始的信号。
-print0使用空字节终止符输出结果。
对于xargs, -I{}参数将{}定义为占位符;你可以使用任何你喜欢的占位符;-0表示输入项为空分隔。
应该使用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 ' ' '/'
丹尼斯的第一个答案是解决问题的答案。但事实上,它不再像标题所暗示的那样,在一个exec中找到几个命令。要回答一个exec与几个命令的事情,我们将不得不寻找其他东西来解决。这里有一个例子:
保留在过去7天内使用一个exec命令使用几个{}引用修改的.log文件的最后10000行
1)看看这个命令会对哪些文件做什么:
find / -name "*.log" -a -type f -a -mtime -7 -exec sh -c "echo tail -10000 {} \> fictmp; echo cat fictmp \> {} " \;
2)这样做:(注意没有更多的“\>”,而只有“>”,这是需要的)
查找/ -name "*.log" -a -type f -a -mtime -7 -exec sh -c "tail -10000 {} > fictmp;Cat fictmp > {};Rm fictmp" \;