Monday, September 07, 2020

Bash script to clean up filenames

I was looking for a way to clean up filenames. Basically, remove a certain string from all files. After spending like five hours searching the Internet and trying different things on my own while learning (a bit) about Bash, I think I have something.
 
cleanname.sh
============
#!/bin/bash
OIFS="$IFS"
IFS=$'\n'
if [[ "$1" == "t" ]]; then
  for filename in `ls | grep "$2"` ; do echo mv \"$filename\" \"${filename//$2/}\"; done > rename.txt
elif [[ "$1" == "c" ]]; then
  for filename in `ls | grep "$2"` ; do echo mv \"$filename\" \"${filename//$2/}\"; done
elif [[ "$1" == "x" ]]; then
  for filename in `ls | grep "$2"` ; do echo mv \"$filename\" \"${filename//$2/}\"; done | /bin/bash
else
  echo "Usage: cleanname.sh <c|x|t> <string>"
  echo " where c for check"
  echo " and x for execute"
  echo " and t to output check results to file rename.txt"
fi
IFS="$OIFS"

Basically, the first parameter is a command to either print out the mv commands that will be used or to actually execute the commands. It is recommended to ALWAYS check the commands first before executing. The commands that will be execute are piped to the screen or to rename.txt. The second parameter is the actual string to remove from the filenames. Use quotes to enclose the string if it contains more than 1 word or has special characters like commas.

The variable IFS is usually space, table, and newline, but in order for the for loop to work properly, it needs to work only on newlines, which is why IFS is changed at the start of the script, and reverted to its original value at the end.

No comments: