| 1 | #! /bin/bash |
| 2 | # rn.sh |
| 3 | |
| 4 | # Very simpleminded filename "rename" utility (based on "lowercase.sh"). |
| 5 | # |
| 6 | # The "ren" utility, by Vladimir Lanin ([email protected]), |
| 7 | #+ does a much better job of this. |
| 8 | |
| 9 | |
| 10 | ARGS=2 |
| 11 | E_BADARGS=85 |
| 12 | ONE=1 # For getting singular/plural right (see below). |
| 13 | |
| 14 | if [ $# -ne "$ARGS" ] |
| 15 | then |
| 16 | echo "Usage: `basename $0` old-pattern new-pattern" |
| 17 | # As in "rn gif jpg", which renames all gif files in working directory to jpg. |
| 18 | exit $E_BADARGS |
| 19 | fi |
| 20 | |
| 21 | number=0 # Keeps track of how many files actually renamed. |
| 22 | |
| 23 | |
| 24 | for filename in *$1* #Traverse all matching files in directory. |
| 25 | do |
| 26 | if [ -f "$filename" ] # If finds match... |
| 27 | then |
| 28 | fname=`basename $filename` # Strip off path. |
| 29 | n=`echo $fname | sed -e "s/$1/$2/"` # Substitute new for old in filename. |
| 30 | mv $fname $n # Rename. |
| 31 | let "number += 1" |
| 32 | fi |
| 33 | done |
| 34 | |
| 35 | if [ "$number" -eq "$ONE" ] # For correct grammar. |
| 36 | then |
| 37 | echo "$number file renamed." |
| 38 | else |
| 39 | echo "$number files renamed." |
| 40 | fi |
| 41 | |
| 42 | exit $? |
| 43 | |
| 44 | |
| 45 | # Exercises: |
| 46 | # --------- |
| 47 | # What types of files will this not work on? |
| 48 | # How can this be fixed? |