4 # @(#) rename.ksh 1.1 94/05/10
5 # 90/06/01 John DuBois (spcecdt@armory.com)
6 # 91/02/25 Improved help info
7 # 92/06/07 remove quotes from around shell pattern as required by new ksh
8 # 94/05/10 Exit if no globbing chars given.
10 # conversion to bash v2 syntax by Chet Ramey
15 All files that match oldpattern will be renamed with the
16 filename components that match the constant parts of oldpattern
17 changed to the corresponding constant parts of newpattern.
18 The components of the filename that match variable parts of
19 oldpattern will be preserved. Variable parts in oldpattern
20 must occur in the same order in newpattern. Variables parts
23 rename \"/tmp/foo*.ba.?\" \"/tmp/new*x?\"
24 All files in /tmp that match foo*.ba.? will have the \"foo\" part
25 replaced by \"new\" and the \".ba.\" part replaced by \"x\"."
28 usage
="usage: $name [-htv] oldpattern newpattern"
31 while getopts "htv" opt
; do
36 *) echo "$name: $usage" 1>&2; exit 2;;
50 if [ ! -e "$1" ]; then
51 echo "$name: no files match $oldpat."
57 # Example oldpat: foo*.a
58 # Example newpat: bar*.b
60 # Examples given for first iteration (in the example, the only interation)
67 # Get leftmost globbing pattern in oldpat
68 pat
=${oldpat#*[\*\?]} # pat=.a
69 pat
=${oldpat%%"$pat"} # pat=foo*
70 pat
=${pat##*[!\?\*]} # pat=*
71 # Find parts before & after pattern
72 oldpre
[i
]=${oldpat%%"$pat"*} # oldpre[1]=foo
73 oldsuf
[i
]=${oldpat#*"$pat"} # oldsuf[1]=.a
74 newpre
[i
]=${newpat%%"$pat"*} # newpre[1]=bar
75 # Get rid of processed part of patterns
76 oldpat
=${oldpat#${oldpre[i]}"$pat"} # oldpat=.a
77 newpat
=${newpat#${newpre[i]}"$pat"} # newpat=.b
82 echo "No globbing chars in pattern." 1>&2
86 oldpre
[i
]=${oldpat%%"$pat"*} # oldpre[2]=.a
87 oldsuf
[i
]=${oldpat#*"$pat"} # oldsuf[2]=.a
88 newpre
[i
]=${newpat%%"$pat"*} # newpre[2]=.b
90 if [ -n "$verbose" ]; then
94 "Old prefix: ${oldpre[j]} Old suffix: ${oldsuf[j]} New prefix: ${newpre[j]}"
99 # Example file: foox.a
103 origname
=$file # origname=foox.a
105 while let "j <= i"; do
106 # Peel off a prefix interation 1 2
107 file=${file#${oldpre[j]}} # file=x.a file=
108 # Save the part of this prefix that is to be retained
109 const
=${file%${oldsuf[j]}} # const=x const=
110 newfile
=$newfile${newpre[j]}$const # newfile=barx newfile=barx.b
111 file=${file#$const} # file=.a file=.a
114 if [ -n "$tell" ]; then
115 echo "Would move \"$origname\" to \"$newfile\"."
117 if [ -n "$verbose" ]; then
118 echo "Moving \"$origname\" to \"$newfile\"."
120 mv $origname $newfile