Bash

使用 WHILE 循環而不是 FOR 循環重命名文件

  • November 3, 2017

考慮到我們有許多名稱為DSC_20170506_170809.JPEG. 為了重命名照片以使其遵循模式Paris_20170506_170809.JPEG,我編寫了以下完美執行的腳本。

for file in *.JPEG; do mv ${file} ${file/DSC/Paris}; done

我的問題是,我們如何使用while循環而不是循環來編寫這個腳本for

在這裡使用while循環沒有任何問題。你只需要做對:

set -- *.jpeg
while (($#)); do
mv -- "${1}" "${1/DSC/Paris}"
shift
done

上面的while循環與循環一樣可靠for(它適用於任何文件名),而後者是 - 在許多情況下 - 最適合使用的工具,前者是一個有效的替代1有它的用途(例如以上可以一次處理三個文件或只處理一定數量的參數等)。


所有這些命令(setwhile..do..doneshift都記錄在 shell 手冊中,它們的名稱是不言自明的……

set -- *.jpeg
# set the positional arguments, i.e. whatever that *.jpeg glob expands to

while (($#)); do
# execute the 'do...' as long as the 'while condition' returns a zero exit status
# the condition here being (($#)) which is arithmetic evaluation - the return
# status is 0 if the arithmetic value of the expression is non-zero; since $#
# holds the number of positional parameters then 'while (($#)); do' means run the
# commands as long as there are positional parameters (i.e. file names)

mv -- "${1}" "${1/DSC/Paris}"
# this renames the current file in the list

shift
# this actually takes a parameter - if it's missing it defaults to '1' so it's
# the same as writing 'shift 1' - it effectively removes $1 (the first positional
# argument) from the list so $2 becomes $1, $3 becomes $2 and so on...
done

1:它不是文本處理工具的替代品,所以永遠不要使用while循環來處理文本。

引用自:https://unix.stackexchange.com/questions/402014