Reputation: 2003
I have a file named /tmp/foo_primary.bar
by default or any other filename a user specified.
How can I rename the file (variable) using bash so that if it contains the string primary
it will change to secondary
and if not, just append _secondary
?
Thanks
Upvotes: 0
Views: 92
Reputation: 242038
You don't need a regex, a pattern will do:
#!/bin/bash
filepath=$1
if [[ $filepath != */* ]] ; then # File in PWD.
filepath=./$filepath
fi
filename=${filepath##*/}
if [[ $filename = *primary* ]] ; then
newname=${filename/primary/secondary}
else
newname=$filename'_secondary'
fi
mv "$filepath" "${filepath%/*}"/"$newname"
Check "Parameter expansion" in man bash
for explanations of the ${...}
constructs.
Upvotes: 1