aironman
aironman

Reputation: 869

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)

Upvotes: 0

Views: 193

Answers (2)

tripleee
tripleee

Reputation: 189397

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!

Upvotes: 2

ua2b
ua2b

Reputation: 282

The original solution mentioned above uses something like (in your case):

NEWNAME="$( echo "$i" | sed -e 's/Sip/SIP/' )"

The content of $(…) is executed in a subshell and must be regular code which i/Sip%/SIP is not. Maybe a typo?

Upvotes: 1

Related Questions