簡體   English   中英

Shell腳本重命名文件

[英]Shell script to rename files

我根據在此找到的示例編寫了一個小的Shell腳本: https : //bbs.archlinux.org/viewtopic.php?id=36305

它需要這個:

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

在此先感謝您幫助我糾正錯誤的代碼。

為什么要使用帶有額外過程的ls進行while循環? 只需在外殼擴展中使用for循環即可。 這是首選方式

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

郵差幾乎擁有它。 對於rename.sh,awk命令不返回任何內容,因此實際上您具有以下shell嘗試執行的命令:

mv rename.sh

因此,錯誤消息“缺少目標文件”

您可以通過測試腳本的文件名(硬編碼或$ 0)並僅在$ FILE與腳本名相同時執行mv命令來解決此問題。

我確實喜歡這樣,並且它完美地更改了文件名。 您可以嘗試如下操作。

mkdir /root/test; touch my\ file{1..10}

vim rename.sh

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

 chmod +x rename.sh
./rename.sh

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM