简体   繁体   中英

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
#!/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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM