2010-08-30 178 views
0

我寫了基於一個例子,我在這裏找到一個小的shell腳本:https://bbs.archlinux.org/viewtopic.php?id=36305shell腳本重命名文件

需要這樣的:

bash-3.2$ ls 
test 001 test 002 test 003 test 004 

,並把它變成:

bash-3.2$ ls 
001 002 003 004 rename.sh 

但它給了我這個錯誤(即使它有效):

bash-3.2$ ./rename.sh 
mv: missing destination file operand after `rename.sh' 
Try `mv --help' for more information. 
`test 001' -> `001' 
`test 002' -> `002' 
`test 003' -> `003' 
`test 004' -> `004' 

雖然它工作正常,但很高興看到我搞砸了,我默認它會把文件放在同一個目錄(這是所需的輸出)。

#!/bin/bash 
ls | while read -r FILE 
do 
     mv -v "$FILE" `echo $FILE | awk -F ' ' '{print $2}'` 
done 

在此先感謝幫助我糾正不正確的代碼。

回答

0

郵差差不多。對於rename.sh,awk命令不返回任何內容因此,實際上你有以下命令的shell試圖執行:

mv rename.sh 

因此錯誤消息「缺少目標文件」

您可以通過測試解決這個問題對於腳本的文件名,無論是硬編碼還是$ 0,並且僅當$ FILE與腳本名稱相等時才執行mv命令。

+0

和修復是隻做包含空格的文件:'ls *''* | '... – ysth 2010-08-30 01:52:09

+0

謝謝你,現在有這麼多的意義! – eddylol 2010-08-30 01:52:54

+0

對不起,我去了一個切線,所以刪除了我的答案:) – PostMan 2010-08-30 02:03:13

1

爲什麼你使用ls帶while循環的額外過程?只需在shell擴展中使用for循環。這是首選的方法

#!/bin/bash 
shopt -s nullglob 
for file in * 
do 
    if [ -f "$file" ];then 
    newfile="${file##* }" 
    mv "$file" $newfile" 
    fi 
done