我试图使用查找-exec与多个命令没有任何成功。有人知道像下面这样的命令是否可行吗?
find *.txt -exec echo "$(tail -1 '{}'),$(ls '{}')" \;
基本上,我试图打印当前目录中每个txt文件的最后一行,并打印在行末,逗号后跟文件名。
我试图使用查找-exec与多个命令没有任何成功。有人知道像下面这样的命令是否可行吗?
find *.txt -exec echo "$(tail -1 '{}'),$(ls '{}')" \;
基本上,我试图打印当前目录中每个txt文件的最后一行,并打印在行末,逗号后跟文件名。
当前回答
感谢Camilo Martin,我得以回答一个相关的问题:
我想做的是
find ... -exec zcat {} | wc -l \;
但这并不奏效。然而,
find ... | while read -r file; do echo "$file: `zcat $file | wc -l`"; done
确实有用,所以谢谢!
其他回答
下面是我的bash脚本,您可以使用它来查找多个文件,然后使用一个命令处理它们。
用法示例。这个命令对每个找到的文件应用一个file linux命令:
./finder.sh file fb2 txt
查找器脚本:
# Find files and process them using an external command.
# Usage:
# ./finder.sh ./processing_script.sh txt fb2 fb2.zip doc docx
counter=0
find_results=()
for ext in "${@:2}"
do
# @see https://stackoverflow.com/a/54561526/10452175
readarray -d '' ext_results < <(find . -type f -name "*.${ext}" -print0)
for file in "${ext_results[@]}"
do
counter=$((counter+1))
find_results+=("${file}")
echo ${counter}") ${file}"
done
done
countOfResults=$((counter))
echo -e "Found ${countOfResults} files.\n"
echo "Processing..."
counter=0
for file in "${find_results[@]}"
do
counter=$((counter+1))
echo -n ${counter}"/${countOfResults}) "
eval "$1 '${file}'"
done
echo "All files have been processed."
我不知道你是否可以用find来做这个,但是另一个解决方案是创建一个shell脚本并用find来运行这个。
lastline.sh:
echo $(tail -1 $1),$1
使脚本可执行
chmod +x lastline.sh
使用找到:
find . -name "*.txt" -exec ./lastline.sh {} \;
另一种方法是这样的:
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可以根据您的需要任意长和复杂。
希望这能有所帮助。
丹尼斯的第一个答案是解决问题的答案。但事实上,它不再像标题所暗示的那样,在一个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" \;
扩展@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