[nSLUG] Removing spaces from file names - note, long lines

Jack Warkentin jwark at bellaliant.net
Mon Nov 10 17:39:28 AST 2014


Hi Everybody

On Wednesday 29 October at the meeting of the Halifax Computer Club I explained how I remove spaces 
from file names. I understand from Frank that there is interest from others in how I do this. So 
here goes.

I use a function in my .bashrc file. Its definition is as follows.

function RemFileNameSps { echo "Renames files so that all spaces are removed"; \
         echo "WORKS ONLY FOR ORDINARY FILES"; \
         [ $# -ne 1 ] && { echo "Exactly one file name required as argument"; exit 1; }; \
         [ -a "$1" ] || { echo "The argument must be a file name"; exit 1; }; \
         file="$1"; oldifs=$IFS; IFS="$(printf '\n\t')"; \
         echo -e "Existing file name is:\t${file}"; \
         newfile=`echo $file | sed -e 's/ //g'`; \
         echo -e "New file name is:\t$newfile"; \
         mv -T "$file" $newfile; \
         IFS=$oldifs; }

However, when the command

declare -f RemFileNameSps

is issued from the command line, the result is


RemFileNameSps ()
{
     echo "Renames files so that all spaces are removed";
     echo "WORKS ONLY FOR ORDINARY FILES";
     [ $# -ne 1 ] && {
         echo "Exactly one file name required as argument";
         exit 1
     };
     [ -a "$1" ] || {
         echo "The argument must be a file name";
         exit 1
     };
     file="$1";
     oldifs=$IFS;
     IFS="$(printf '\n\t')";
     echo -e "Existing file name is:\t${file}";
     newfile=`echo $file | sed -e 's/ //g'`;
     echo -e "New file name is:\t$newfile";
     mv --strip-trailing-slashes -T "$file" $newfile;
     IFS=$oldifs
}

So either form could be used in a .bashrc file.

If you want to bulk remove spaces from several file names, first use ls to make absolutely sure that 
you specify all and only the files you want to perform this on. Then issue

for file in <specify files to be operated on>; do RemFileNameSps "$file"; done

The quotes ( " ) around $file at the end of this ( as in "$file" ) are essential. If I leave them 
out the terminal window crashes.

Another bulk file renaming that I do occurs when I copy files from a FAT file system and want to 
translate uppercase file names to lowercase names.  For this I do

for file in <specify files to be operated on>; do mv $file `echo $file | tr [A-Z] [a-z]`; done

I hope you find these techniques useful.

Regards

Jack

Jack Warkentin, phone 902-404-0457, email jwark at bellaliant.net
39 Inverness Avenue, Halifax, Nova Scotia, Canada, B3P 1X6


More information about the nSLUG mailing list