## 需求    ## 撰寫bash ```bash= # Get list of student IDs from file IFS=$'\r\n' GLOBIGNORE='*' command eval 'student_ids=($(cat student_id))' # Create directories for different file types mkdir -p compressed_files/zip mkdir -p compressed_files/tar mkdir -p compressed_files/rar mkdir -p compressed_files/unknown # Loop through compressed_files directory for file in compressed_files/*; do # Get file extension ext=${file##*.} # Check if file is a compressed archive and is not empty if [[ "$ext" =~ ^(zip|tar|rar|gz)$ ]] && [[ -s "$file" ]]; then # Extract student ID from file name id=$(echo "$file" | grep -oE '[a-zA-Z][0-9]+') # Check if student ID is in list of IDs if ! [[ " ${student_ids[@]} " =~ " $id " ]]; then # Write missing student ID to missing_list.txt echo "$id" >> missing_list.txt fi # Move file to appropriate directory based on extension case "$ext" in zip) unzip "$file" -d compressed_files/zip ;; tar | gz) tar xf "$file" -C compressed_files/tar ;; rar) unrar x "$file" compressed_files/rar ;; esac # Remove original file rm "$file" elif [[ "$ext" != "zip" && "$ext" != "tar" && "$ext" != "rar" ]]; then # Check if file is a directory if [[ -d "$file" ]]; then continue fi # Write wrong file format to wrong_list.txt id=$(echo "$file" | grep -oE '[a-zA-Z][0-9]+') echo "$id" >> wrong_list.txt mv "$file" "compressed_files/unknown/" fi done ``` 1. `IFS=$'\r\n' GLOBIGNORE='*' command eval 'student_ids=($(cat student_id))'`<br>使用 `cat` 指令讀取 `student_id.txt` 中所有行並儲存在一個數組中。 1. `mkdir -p compressed_files/xxx`<br>建立解壓縮後不同類型的目錄,分別為`zip、tar、rar` 和 `unknown` 目錄。 2. `for file in compressed_files/*; do`:循環遍歷 `compressed_files` 目錄中的所有文件和文件夾。 3. `ext=${file##*.}`:獲取檔案格式名稱,使用 `${file##*.}` 取得最後一個句點之後的所有內容。 4. `if [[ "$ext" =~ ^(zip|tar|rar|gz)$ ]] && [[ -s "$file" ]]; then`:如果文件是壓縮檔案且不為空,則繼續執行操作。 5. `id=$(echo "$file" | grep -oE '[a-zA-Z][0-9]+')`:提取文件名中的學生 `ID`,使用 `grep` 命令查找由一個英文字母和一個或多個數字組成的模式。 6. `if ! [[ " ${student_ids[@]} " =~ " $id " ]]; then`:檢查學生 ID 是否存在於 `student_id` 文件中,如果不存在,則將其添加到 `missing_list.txt` 文件中。 7. `case "$ext" in ...`:使用 `case` 語句處理不同的文件類型,將三種不同類型壓縮檔案格式解壓縮 8. `rm "$file"`:刪除原始檔案。 9. `elif [[ "$ext" != "zip" && "$ext" != "tar" && "$ext" != "rar" && "$ext" != "gz" ]]; then`:如果文件不是 `zip、tar、rar` 或 `gz`,則繼續執行操作。 10. `if [[ -d "$file" ]]; then`:檢查文件是否是目錄,如果是的話就跳過,避免資料夾被移進去`unknown` 目錄。 11. 將上傳錯誤學生的`ID`寫入 `wrong_list.txt`,並將檔案移入`unknown` 目錄。 ## Run bash 打開終端機或命令列界面。 輸入cd命令,進入存放Bash腳本的目錄。 輸入以下命令,使Bash腳本具有執行權限(script_name.sh是Bash腳本檔案名稱): ```bash= chmod +x script_name.sh ``` 輸入以下命令運行Bash腳本: ```bash= ./script_name.sh ``` ## 結語 等待 `bash` 跑完,檔案就會依照不同壓縮檔案格式解壓縮並放入個別的資料夾內,並將上傳錯誤的學生`ID`,以及為上傳檔案的學生分別記錄在 `txt` 文件中。
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up