Search code examples
bashbatch-rename

why this bash script is not working when trying to rename existing files


i have this script and a dir file with some Sip_* files and i need to rename them to SIP_*

for i in Sip_R*.csv
do
   echo "processing $i"
   NEWNAME="$(i/Sip%/SIP)"
   echo "newname is $NEWNAME"
   mv -- "$i" "$NEWNAME"
done

and i receiving

 processing Sip_Reg-generated1415879496958.csv
 digest-reg-files.sh: line 5: i/Sip%/SIP: No such file or directory
 newname is
 mv: cannot move `Sip_Reg-generated1415879496958.csv' to `': No such file or directory
 processing Sip_Reg-generated1415879504694.csv
 digest-reg-files.sh: line 5: i/Sip%/SIP: No such file or directory
 newname is
 mv: cannot move `Sip_Reg-generated1415879504694.csv' to `': No such file or directory

I have modified the solution provided by Renaming multiples files with a bash loop and it is not working.

The machine is some centos, 2.6.32-358.el6.x86_64 and bash version is 4.1.2(1)-release (x86_64-redhat-linux-gnu)


Solution

  • Your brackets are wacky. The syntax for string substitution in Bash uses curly braces, not round parentheses.

    Also, like the answer you link to explains, the percent sign anchors the substitution to the end of the string, which is not what you want here. Use /# instead to anchor to the beginning of the string; or you could use ${i/Sip/SIP} to not anchor at all (you already know the first occurrence is at the beginning of the string anyway).

    NEWNAME="${i/#Sip/SIP}"
    

    Kudos for properly quoting everything!