Home > Bash, Computers, Linux, Programming > Dir/File space2score

Dir/File space2score

I wrote this little script because I had to manage a task for creating a file naming scheme. It will replace all spaces in file names and subdirectories of a given directory with an underscore.

#!/bin/bash
#####
## Program:
##    File/Directory Formatter
## Author:
##    Kyle Rizzo
##    lifeforce0 {at} gmail {dot} com
##    https://lifeforce4.wordpress.com
## Summary:
##    This little script will search though all files and subdirs of a given
##    location then starting from the bottom up will replace ' '(spaces) with
##    '_' underscores.
#####

## Coloring Schemes
NC='\033[0;37m'
RED='\033[1;31m'
YELLOW='\033[1;33m'
BLUE='\033[1;34m'
CYAN='\033[1;36m'
WHITE='\033[1;37m'

## Find only Files with spaces and replace the spaces with underscores
#find $1 -depth -type f -name '* *' -print | while IFS= read -r file; do
## Find only Directories with spaces and replace the spaces with underscores
#find $1 -depth -type d -name '* *' -print | while IFS= read -r file; do
## Find any files/directories from the given path if none specified used ./
## and replace spaces with underscores in all names.
find $1 -depth -name '* *' -print | while IFS= read -r file; do
   file=$file
   basedir=${file%/*}
   filename=${file##*/}
   newfilename=$(echo "$filename" | tr -s ' ' _)

   echo -en "\n$WHITE"
   echo -en "Renaming $CYAN$filename$WHITE to $YELLOW$newfilename$WHITE \
in $BLUE$basedir/"

## Check if the file is a directory or a file with in a directory.
## Set newfile accordingly
   if [ ! "$basedir" = "$file" ]; then
      newfile="$basedir/$newfilename"
   else
      newfile="./$newfilename"
   fi

## Check to see if a file exists with that name
## Refuse to over wright the file if it does.
   if [ ! -e "$newfile" ]; then
      mv "$file" "$newfile"
   else
      echo "$RED\Refusing to overwrite $BLUE$newfile"
   fi
done
echo -en "$NC\n"
Advertisements
Categories: Bash, Computers, Linux, Programming
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: