Wednesday, May 20, 2015

Space out on Solaris 10

Removing spaces from file names... seems like everyone has their own way to do it. Here's what I ended up putting in my Solaris 10 ~/.bashrc :

function despace()
{
    while IFS='' read FILE
    do
        NEWFILE=`echo "$FILE" | sed -e 's/ /_/g'`

        if [ "$FILE" = "$NEWFILE" ]
        then
            echo "No spaces detected in [$FILE]"
            continue
        fi

        if [ -e "$NEWFILE" ]
        then
            echo "$NEWFILE already exists, not going to overwite it"
        else
            echo "Renaming [$FILE] to [$NEWFILE]"
            mv "$FILE" "$NEWFILE"
        fi
    done
}


Use the command like this:

$ ls * | despace
Renaming [CT.SABR test 5.1.dcm] to [CT.SABR_test_5.1.dcm]
Renaming [CT.SABR test 5.10.dcm] to [CT.SABR_test_5.10.dcm]
Renaming [CT.SABR test 5.100.dcm] to [CT.SABR_test_5.100.dcm]

If a file by the name we're changing to already exists, it will not get over-written:

$ ls * | despace
Renaming [CT.SABR_test_5.1.dcm] to [CT.SABR_test_5.1.dcm]
CT.SABR_test_5.1.dcm already exists, not going to overwite it

The IFS='' is needed to catch trailing spaces on filenames (I know, no sane person would do that, but included for the sake of completeness). If you pass it filenames without spaces, it tells you and skips them.

Note: on Linux you can use rename, but that doesn't live on Solaris 10 by default, and I'm working with the tools I have

No comments:

Post a Comment