![](/img/trans.png)
[英]Bash SH Script - Rename File with specific extension + Move to specific location
[英]Bash script to rename file extension
#!/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 rename_file_extensions.sh . txt html
輸出示例:
Use of uninitialized value $2 in regexp compilation at (eval 6) line 1.
line 1
包含上面的if statement
。 參數$2
是txt
。 因此,我對它所指的感到困惑。
我可以運行以下行,它可以完美運行,但是我想讓它接受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
bash rename_file_extensions.sh . txt html
bash rename_file_extensions.sh . txt html
。
請幫忙!
謝謝!
要獲取shell解釋的參數,請刪除單引號:
嘗試
find "$1" -name "*.$2*" -exec rename "s/\.${2}\$/.${3}/" '{}' \;
或(如果您想保留報價)
find "$1" -name "*.$2*" -exec rename 's/\.'"${2}"'$/.'"${3}"'/' '{}' \;
(並且我會將-name
的完整參數括在雙引號中,否則bash可以在當前目錄中匹配某些文件時直接擴展該參數)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.