Shell,删除名称末尾的空格

时间:2017-09-18 15:47:06

标签: linux bash shell quoting

我在名称的末尾有一些带空格的文件或目录。 shell可以删除吗?

由于

2 个答案:

答案 0 :(得分:3)

for f in *[[:space:]]; do                    # iterate over filenames ending in whitespace
  [[ -e $f || -L $f ]] || continue           # ignore nonexistent results (ie. empty glob)
  d=$f                                       # initialize destination variable
  while [[ $d = *[[:space:]] ]]; do          # as long as dest variable ends in whitespace
    d=${d:0:((${#d} - 1))}                   # ...trim the last character from it.
  done
  printf 'Renaming %q to %q\n' "$f" "$d" >&2 # log what we're going to do
  mv -- "$f" "$d"                            # and do it.
done

请参阅:

  • Parameter expansion,用于修剪最后一个字符的语法(${varname:start:length}从位置start开始获取给定长度的切片。)
  • Globbing,用于列出以空格结尾的文件名的机制。
  • The classic for loop,用于迭代glob结果。

printf %q说明符是一个bash扩展,它以一种方式将字符串格式化为eval回原始字符串的内容 - 因此,它可以打印一个以空格结尾的名称name\ 'name ',但会以某种方式确保读者可以看到空格。

答案 1 :(得分:0)

这是一个没有外部调用的本机POSIX shell解决方案。

#!/bin/sh

for file in *[[:space:]]; do            # loop over files/dirs ending in space(s)
  [ -e "$file" ] || continue            # skip empty results (no-op)
  new_file="${file%[[:space:]]}"        # save w/out first trailing space char
  while [ "$file" != "$new_file" ]; do  # while the last truncation does nothing
    file="${file%[[:space:]]}"          # truncate one more trailing space char
  done
  # rename, state the action (-v), prompt before overwriting files (-i)
  mv -vi -- "$file" "$new_file"
done