Bash script: file/folder names with spaces, renaming, reordering words

Problem: I have various ebooks, in folders named like this:

Adams, Douglas
Anthony, Piers
Barry, Max
Batman vs Predator
Chalker, Jack L
Farmer, Philip Jose
Heinlein, Robert
Hubbard, L. Ron
L'Engle, Madeleine
Neil Gaiman
Niven, Larry
Pullman, Philip
Rowling, J. K
Tepper, Sherri S
Terry Pratchett

I want a script that will

  • rename folders like “Anthony, Piers” to “Piers Anthony”
  • rename folders like “Farmer, Philip Jose” to “Philip Jose Farmer”
  • for each folder, prompt user before renaming

Solution: bash script

NUMFILES=`ls -1 | wc -l | awk '{print $1}'`
while [ $NUM -le $NUMFILES ]
  BNAME=`ls -1 | sed -n "$NUM p"` #backwards file/folder name to be changed
  NUMWORDS=`echo $BNAME | wc -w | awk '{print $1}'`
  case $NUMWORDS in
    2) FNAME=`echo $BNAME | sed 's/,//g' | awk '{print $2, $1}'` #rename "Adams, Douglas" to "Douglas Adams"
    3) FNAME=`echo $BNAME | sed 's/,//g' | awk '{print $2, $3, $1}'` #rename "Tepper, Sheri S"
  read -p "Rename \"$BNAME\" to \"$FNAME\" (Y/N)? " DOIT
  if [ "$DOIT" = "Y" -o "$DOIT" = "y" ]
    mv "$BNAME" "$FNAME"


$ swap2
Rename "Adams, Douglas" to "Douglas Adams" (Y/N)? y
Rename "Barry, Max" to "Max Barry" (Y/N)? y
Rename "Chalker, Jack L" to "Jack L Chalker" (Y/N)? y
Rename "Farmer, Philip Jose" to "Philip Jose Farmer" (Y/N)? y


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s