2014-05-31

Bulk Extension Renamer - bash

As a quick counter-point to my earlier PowerShell script, here's my equivalent in bash:


1:  #!/bin/bash  
2:    
3:  if [ $# -lt 2 ]; then  
4:      echo -e "\e[33mUsage: $0 <current extension> <new extension>\e[0m"  
5:      exit 1  
6:  fi  
7:    
8:  for fileName in *.$1; do  
9:      newFileName=${fileName/.$1/.$2}  
10:      if [ -f "$newFileName" ]; then  
11:          echo -e "\e[31mNot renaming \e[1m$fileName\e[22m to \e[1m$newFileName\e[22m -- File exists."  
12:      elif [ -d "$newFileName" ]; then  
13:          echo -e "\e[31mNot renaming \e[1m$fileName\e[22m to \e[1m$newFileName\e[22m -- Is a directory."  
14:      else  
15:                 if [ -w "$fileName" ]; then  
16:                      mv "$fileName" "$newFileName"  
17:                       echo -e "\e[1;32m$fileName\e[22m renamed to \e[1m$newFileName\e[0m"  
18:                 else  
19:                      echo -e "\e[31mUnable to rename \e[1m$fileName\e[22m - file is not writable\e[0m"  
20:                 fi  
21:      fi  
22:  done  

Short, neat and to the point. The only slightly unwieldy part is the rather ugly ANSI color codes.

As for functionality, it checks if the file already exists (or a directory with the same name exists) and throws an error if so. It also tests if the original file is writable before attempting to move it and errors out if it isn't.

Here it is running:
 

No comments:

Post a Comment