多少个文件中查找发现了什么? [英] how many files find found?
问题描述
我在写一个脚本,在这里我要报错了,如果我在寻找的文件在多个位置存在,并且告诉用户位置(查找结果)。所以我有一个发现像:
file_location = $($找到DIR -name $文件-print)
我想它应该是简单的,看文件是否在多个地方发现,但我一定不能匹配找到什么用途与分离的结果(好像空间有时和一个换行符等)。因此,而不是上匹配,我想看看是否有$ file_location $文件之后的任何字符。
我检查
回声$ file_location| grep的-q$ {}文件。然后
这仍然无法正常工作。所以我想我不在乎我用的,除了我想捕捉$ file_location作为查找的结果,然后检查。您能否提供一个很好的方式?
找到= $(发现$目录-name$文件-ls)
数= $(WC -l<<<$找到了)
如果[$伯爵-gt 1]
然后
回声我发现不止一个:
回声$发现
科幻
有关零的比赛中,你仍然会收到一个1,因为不透明的方式外壳的条的使用 $()
运营商尾随的换行符,所以实际上,第一个线路输出和零线输出到底两者一行。参见 XXD<<<
为换行的自动追加示范输入再次使用时。一个简单的方法来规避这是在字符串的开头加上一个假的换行,所以没有空字符串可能发生:找到= $(回声;发现...)
,和然后减去一个来自行数
编辑:我改变了的使用-printf%P \\ N
在回答 -ls
它执行正确的换行的报价。在其中会搞乱了计数,否则用换行文件名
I'm writing a script where I want to error out if the file I'm searching for exists in multiple locations, and tell the user the locations (the find results). So I've got a find like:
file_location=$(find $dir -name $file -print)
I'm thinking it should be simple to see if the file is found in multiple places, but I must not be matching what find uses to separate results with (seems like space sometimes, and a newline others). As such, rather than matching on that, I want to see if there are any characters after $file in $file_location.
I'm checking for
echo "$file_location" | grep -q "${file}."; then
and this still doesn't work. So I guess I don't care what I use, except I want to capture $file_location as a result of the find, and then check that. Can you suggest a good way?
found=$(find "$dir" -name "$file" -ls)
count=$(wc -l <<< "$found")
if [ "$count" -gt 1 ]
then
echo "I found more than one:"
echo "$found"
fi
For zero matches found you will still receive a 1 because of the intransparent way the shell strips a trailing newline with the $()
operator, so effectively one line output and zero lines output are both one line in the end. See xxd <<< ""
for demonstration of the automatic appending of a newline when used as input again. A simple way to circumvent this is to add a fake newline in the beginning of the string, so no empty string can happen: found=$(echo; find …)
, and then subtract one from the number of lines.
EDIT: I changed the usage of -printf "%p\n"
in my answer to -ls
which performs a proper quoting of newlines. Otherwise file names with newlines in them would mess up the counting.
这篇关于多少个文件中查找发现了什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!