我试图使用查找-exec与多个命令没有任何成功。有人知道像下面这样的命令是否可行吗?
find *.txt -exec echo "$(tail -1 '{}'),$(ls '{}')" \;
基本上,我试图打印当前目录中每个txt文件的最后一行,并打印在行末,逗号后跟文件名。
我试图使用查找-exec与多个命令没有任何成功。有人知道像下面这样的命令是否可行吗?
find *.txt -exec echo "$(tail -1 '{}'),$(ls '{}')" \;
基本上,我试图打印当前目录中每个txt文件的最后一行,并打印在行末,逗号后跟文件名。
当前回答
find . -type d -exec sh -c "echo -n {}; echo -n ' x '; echo {}" \;
其他回答
我通常将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
下面是我的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."
扩展@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
应该使用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命令接受多个-exec部分。例如:
find . -name "*.txt" -exec echo {} \; -exec grep banana {} \;
注意,在这种情况下,只有当第一个命令成功返回时,第二个命令才会运行,正如@Caleb提到的那样。如果你想让两个命令都运行,不管它们成功或失败,你可以使用这个结构:
find . -name "*.txt" \( -exec echo {} \; -o -exec true \; \) -exec grep banana {} \;