所以我试图编写一个脚本,搜索用户给出的目录,查找用户也提供的特定扩展名的所有文件。到目前为止,我的脚本只搜索我的主文件夹的mybooks目录,无论给出什么目录。到目前为止,该脚本如下所示:
# Prompts the user to input a directory
# Saves input in variable dir
echo -n "Please enter a directory to search in: "
read dir
if [ ! -d /$dir ]; then
echo "You didn't enter a valid directory path. Please try again."
fi
# Prompts the user to input a file extension to search for
# Saves input in variable ext
echo -n "Please enter a file extension to search for: "
read ext
echo "I will now search for files ending in "$ext
# Searches for files that match the given conditions and prints them
find $dir -type f -name $ext
for file in *$ext
do
echo $file
done
#TODO: put code here that prints the names of the largest and smallest files
# that were found in the search
echo "The largest file was: "
echo "The smallest file was: "
因此,您可以看到永远不会提供mybooks目录。以下是示例输出:
Please enter a directory to search in: /var/books
Please enter a file extension to search for: .txt
I will now search for files ending in .txt
hound.txt
list-lines.txt
numbers.txt
The largest file was:
The smallest file was:
$ls /var/books/
arthur-conan-doyle_The-hound-of-baskervilles.txt arthur-conan-doyle_The-valley-of-fear.txt mary-roberts-rinehart_The-circular-staircase.txt
arthur-conan-doyle_The-hound-of-baskervilles.zip arthur-conan-doyle_The-valley-of-fear.zip
关于我做错了什么或从哪里去的任何建议?谢谢!
答案 0 :(得分:1)
替换它:
find $dir -type f -name $ext
for file in *$ext
do
echo $file
done
有了这个:
find "$dir" -type f -name "*.$ext"
find $dir -type f -name $ext
以上搜索$dir
查找名称正好 $ext
的文件。很可能没有这样的文件。
相反,以下内容忽略$dir
并在当前目录中搜索扩展名为$ext
的文件:
for file in *$ext
do
echo $file
done
请注意,由于$dir
或$ext
可能包含空格或其他困难字符,因此它们应为双引号。