实现针对文件扩展名的 case
语句
在这一步中,你将学习如何在 shell 脚本中使用 case
语句来处理不同的文件扩展名。
假设你有一个包含各种文件的目录,并且你希望根据文件扩展名执行不同的操作。你可以使用 case
语句来实现这一点。
首先,创建一个新目录并导航到该目录:
mkdir ~/project/files
cd ~/project/files
现在,让我们创建一些具有不同扩展名的示例文件:
touch file1.txt file2.pdf file3.jpg file4.png file5.gif file6.doc
接下来,在 ~/project/files
目录中创建一个名为 file_operations.sh
的新 shell 脚本:
nano file_operations.sh
将以下代码添加到脚本中:
#!/bin/bash
for file in *; do
case "$file" in
*.txt)
echo "Text file: $file"
;;
*.pdf)
echo "PDF file: $file"
;;
*.jpg | *.png | *.gif)
echo "Image file: $file"
;;
*.doc)
echo "Document file: $file"
;;
*)
echo "Unsupported file type: $file"
;;
esac
done
保存并退出文件。
使脚本可执行:
chmod +x file_operations.sh
现在,运行脚本:
./file_operations.sh
示例输出:
Text file: file1.txt
PDF file: file2.pdf
Image file: file3.jpg
Image file: file4.png
Image file: file5.gif
Document file: file6.doc
在脚本中,case
语句检查文件扩展名并执行相应的操作。*.txt
、*.pdf
、*.jpg | *.png | *.gif
和 *.doc
模式匹配文件扩展名,并为每种文件类型打印相应的消息。*
模式是默认情况,用于处理任何不支持的文件类型。
此示例演示了如何使用 case
语句根据文件扩展名自动化文件管理任务。