简体   繁体   中英

Shell script to rename files

I wrote a small shell script based on an example I found here: https://bbs.archlinux.org/viewtopic.php?id=36305

it takes this:

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

and turns it into:

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

However it gives me this error (even though it works):

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'

Though it works correctly, it would be nice to see where I messed up, I assumed by default it would put the files in the same directory (this is the desired output).

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

Thanks in advance for helping me correct my incorrect code.

why are you using ls with an extra process to while loop? Just use a for loop with shell expansion. This is preferred way

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

Postman almost has it. For rename.sh, the awk command returns nothing so in effect you have the following command the shell attempts to execute:

mv rename.sh

hence the error message "missing destination file"

you can fix this by testing for the filename of the script, either hardcoded or $0, and executing the mv command only if $FILE does equal the script name.

I did like this and it is perfectly changing the filenames. You may try like below.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM