Jacqueline Ray
Jacqueline Ray

Reputation: 21

Bash Script to remove leading and trailing spaces for all files in a directory

I would like to just add it to Automator and let the user choose the directory in which it runs. One Drive will not upload files with space. I managed to remove all spaces but not remove all spaces from the beginning and the end.

My code:

for f in "$1"/*; do
  dir=$(dirname "$f")
  file=$(basename "$f")
  mv "$f" "${dir}/${file//[^0-9A-Za-z.]}"
done

Upvotes: 1

Views: 956

Answers (1)

Charles Duffy
Charles Duffy

Reputation: 295687

#!/usr/bin/env bash

shopt -s extglob                        # Enable extended globbing syntax
for path in "$1"/*; do
  file=${path##*/}                      # Trim directory name
  file=${file##+([[:space:]])}          # Trim leading spaces
  file=${file%%+([[:space:]])}          # Trim trailing spaces
  if [[ $file != "${path##*/}" ]]; then # Skip files that aren't changed
    mv -- "$path" "$1/${file}"
  fi
done

Notes:

  • A shell needs to be started with bash, not sh, to ensure that extensions (such as extglobbing and [[ ]]) are available.
  • There's no need to call dirname, since we always know the directory name: It's in $1.
  • extglob syntax extends regular glob expressions to have power comparable to regexes. +([[:space:]]) is extglob for "one or more spaces", whereas the ${var%%pattern} and ${var##pattern} remove as many characters matching pattern as possible from the back or front, respectively, of a variable's value.
  • There's no point to running a mv when the filename didn't need to change, so we can optimize a bit by checking first.

Upvotes: 3

Related Questions