更新时间:2023-02-16 12:27:06
找到= $(发现$目录-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.