简体   繁体   English

Bash脚本删除目录中所有文件的前导和尾随空格

[英]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. 我只想将其添加到Automator中,然后让用户选择运行它的目录。 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. Shell必须以bash而不是sh开头,以确保扩展名(例如extglobbing和[[ ]] )可用。
  • There's no need to call dirname , since we always know the directory name: It's in $1 . 不需要调用dirname ,因为我们总是知道目录名称:它在$1
  • extglob syntax extends regular glob expressions to have power comparable to regexes. extglob语法扩展了常规glob表达式,使其具有与正则表达式相当的功能。 +([[: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. +([[:space:]])是extglob,表示“一个或多个空格”,而${var%%pattern}${var##pattern}从后面或前面删除尽可能多的与pattern匹配的字符分别代表变量的值。
  • 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. 当不需要更改文件名时,没有必要运行mv ,因此我们可以通过首先检查来进行一些优化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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