我试图使用查找-exec与多个命令没有任何成功。有人知道像下面这样的命令是否可行吗?
find *.txt -exec echo "$(tail -1 '{}'),$(ls '{}')" \;
基本上,我试图打印当前目录中每个txt文件的最后一行,并打印在行末,逗号后跟文件名。
我试图使用查找-exec与多个命令没有任何成功。有人知道像下面这样的命令是否可行吗?
find *.txt -exec echo "$(tail -1 '{}'),$(ls '{}')" \;
基本上,我试图打印当前目录中每个txt文件的最后一行,并打印在行末,逗号后跟文件名。
当前回答
扩展@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
其他回答
下面是我的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."
我找到了这个解决方案(可能已经在评论中说过了,但我找不到任何答案)
你可以使用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
感谢Camilo Martin,我得以回答一个相关的问题:
我想做的是
find ... -exec zcat {} | wc -l \;
但这并不奏效。然而,
find ... | while read -r file; do echo "$file: `zcat $file | wc -l`"; done
确实有用,所以谢谢!
有一个更简单的方法:
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+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表示输入项为空分隔。