2016-08-19 184 views
0
#!/bin/bash 

if [[ "$#" -lt 3 ]]; then 
    echo "USAGE: enter the following arguments: 
    1st argument = starting directory path (e.g. . for working directory) 
    2nd argument = old file extension (e.g. txt) 
    3rd argument = new file extension (e.g. html 
    Note: Do not enter any . or \. for the 2nd and 3rd arguments 
    " 
else 
    find "$1" -name *."$2"* -exec rename 's/\."${2}"$/."${3}"/' '{}' \; 
fi 

示例輸入:bash腳本重命名文件的擴展名

bash rename_file_extensions.sh . txt html 

輸出示例:

Use of uninitialized value $2 in regexp compilation at (eval 6) line 1. 

line 1包含上述if statement。參數$2txt。所以,我對它指的是什麼感到困惑。

我可以運行下面的線,它完美的作品,但我想擁有它接受bash的論點:

find . -name "*.txt.html*" -exec rename 's/\.txt.html.html.html$/.html/' '{}' \; 

在這種情況下,你可以看到,有很多不正確的文件擴展名。這條線糾正了所有這些。

我試圖編輯find行:

find "${1}" -name '*."$2"*' -exec rename 's/\."${2}"$/."${3}"/' '{}' \; 

這讓我向前沒有錯誤;然而,沒有輸出,並且當我運行以下命令bash rename_file_extensions.sh . txt html時,並沒有將txt擴展名更改爲html

請幫忙!

謝謝!

回答

1

獲得通過shell來解釋參數,落單引號:

嘗試

find "$1" -name "*.$2*" -exec rename "s/\.${2}\$/.${3}/" '{}' \; 

或者(如果你想保持引號)

find "$1" -name "*.$2*" -exec rename 's/\.'"${2}"'$/.'"${3}"'/' '{}' \; 

(我會附上-name在雙引號或bash中的完整參數可以直接擴展參數,如果某些文件在當前目錄中匹配)

+0

我使用'find'$ 1「-name」*。$ 2 *「-exec rename's/\'。」$ {2}「'$ /。'」$ {3}「'/''{}' \;'而且效果很棒!謝謝! – Debug255