Kill space in filename recursively

I recently wrote a little script to backup my files, but if a filename contains a space, bash couldn't access it correctly. I worte another script to solve this.

save the following text to killspace, then run

chmod +x killspace



#!/bin/bash
# killspace v0.1
# License: GPLv2
# by AZ (Aitjcize) 
#
# usage: killspace [--dry] [path]
# Present working directory is used if path is not set
# Use `--dry' to run the script without really modify the filename, this is
# useful when you want to find out which filename contains space.

# you can change the delimiter and seperator if you want.
# The only restriction for the delimiter is that it shouldn't appear in any of
# your filename.

delimiter='|DL|'
seperator='_'

# functions

killdir() {
  cd "$1"
  echo In $1
  for fn in `ls | sed "s/ /$delimiter/g"`
  do
    rfn=`echo $fn | sed "s/$delimiter/ /g"`
    cfn=`echo $fn | sed "s/$delimiter/$seperator/g"`
    if [ "$rfn" != "$cfn" ]; then
      if [ $dry == 0 ]; then
        mv "$rfn" "$cfn"
      else
        cfn=$rfn
      fi
      echo -e "\033[01;36m* $rfn -> $cfn \033[00m"
    fi
    if [ -d "$cfn" ]; then
      killdir "$cfn"
    fi
  done
  cd ..
}

# main

dry=0

if [ "$1" == "--dry" ]; then
  echo "Dry run mode."
  dry=1
  shift
fi

if [ -n "$1" ]; then
  kdir=$1
else
  kdir=`pwd`
fi

if [ $dry == 0 ]; then
  echo -n "Do you want to change all space in filename to \`$seperator' in $kdir? [y/N] "
  read yn
  if [ "$yn" != "y" ] && [ "$yn" != "yes" ]; then
    exit 0
  fi
fi

# start recursive kill
killdir $kdir

# end

留言

這個網誌中的熱門文章

決定了!!!

P.S. I Love You

Tips: PPTP client on Openwrt