Based on Google's Style Guide, I made the following script. The script should take files like a.txt
and b.txt
and change them to PREFIX_1_prefix_a.txt
and PREFIX_1_prefix_b.txt
. However, when I enter:
$ sh rename_enum.sh -n 100 -P X -p Y
I expect X_100_Y_a.txt
and X_101_Y_b.txt
, but I get _1_a.txt
and _2_b.txt
. Can anyone tell me what I'm doing wrong?
#!/bin/bash
#verbose='false'
nflag=1
Pflag=''
pflag='_'
files='*.txt'
while getopts 'nPpf' flag; do
case "${flag}" in
n) nflag="${OPTARG}" ;;
P) Pflag="${OPTARG}_" ;;
p) pflag="_${OPTARG}_" ;;
f) files="${OPTARG}" ;;
#v) verbose='true' ;;
*) error "Unexpected option ${flag}" ;;
esac
done
for i in ${files}
do
mv "$i" "${Pflag}${nflag}${pflag}$i"
nflag=$((nflag + 1))
done
I found this man page which explains that if a flag has an argument, then it should be followed by a colon. All I had to do was change the line...
while getopts 'nPpf' flag; do
... to ...
while getopts 'n:P:p:f:' flag; do
... and I got the desired result. Thanks for the comments, though!