【问题标题】:Renaming batch files, but error occurs when there is space in the file name. Need a fix! Bash [duplicate]重命名批处理文件,但文件名中有空格时出错。需要修复!重击[重复]
【发布时间】:2014-12-02 14:45:28
【问题描述】:

所以我的代码有效。它正在做我想做的事。本质上,我的脚本重命名文件以匹配放置它们的最后两个目录,然后是零填充。它还需要一个参数,如果您输入目录,它将更改指定目录中的文件。

这是我的代码:

r="$@"
if [ -d "$r" ]; then            # if string exists and is a directory then do the following commands
  cd "$r"                       # change directory to the specified name
  echo "$r"                     # print directory name
elif [ -z "$1" ]; then          # if string argument is null then do following command
  echo "Current Directory"      # Print Current Directory
else                            # if string is not a directory or null then do nothing
  echo "No such Directory"      # print No such Directory
fi

e=`pwd | awk -F/ '{ print $(NF-1) "_" $NF }'`   # print current directory | print only the last two fields
echo $e
X=1;
for i in `ls -1`; do                            # loop. rename all files in directory to "$e" with 4 zeroes padding.
  mv $i $e.$(printf %04d.%s ${X%.*} ${i##*.})   # only .jpg files for now, but can be changed to all files.
  let X="$X+1"
done

这是输出:

Testdir_pics.0001.jpg
Testdir_pics.0002.jpg
...

但是,正如标题所暗示的那样,当文件名中包含空格时,它会产生错误。我该如何解决这个问题?

【问题讨论】:

  • 您已使用 OSX、Bash、Unix 和 Batch (Windows) 标记您的问题。您实际使用的是哪个系统??
  • 通过SpellCheck运行你的脚本
  • 对不起,我只是在我的 Mac OSX 中使用终端

标签: macos bash unix batch-file rename


【解决方案1】:

如果文件名中有空格,那么这两行会失败:

for i in `ls -1`; do 
  mv $i $e.$(printf %04d.%s ${X%.*} ${i##*.})

将它们替换为:

for i in *; do 
  mv "$i" "$e.$(printf %04d.%s "${X%.*}" "${i##*.}")"

评论:

  • for i in * 适用于所有文件名,即使是那些字符最难的文件名。相比之下,for i in $(ls -1) 的表述非常脆弱。

  • 除非出于某种奇怪的原因,您确实希望对变量执行分词,否则请始终将它们放在双引号中。因此,mv $i ... 应替换为 mv "$1" ...

【讨论】:

  • 除非你知道你有理由不这样做,否则总是引用变量扩展。有关 ls -1 -> * 更改,请参阅 mywiki.wooledge.org/ParsingLs
  • 我明白了。有用!谢谢!
猜你喜欢
  • 1970-01-01
  • 2013-10-08
  • 1970-01-01
  • 1970-01-01
  • 2019-06-08
  • 2013-10-31
  • 1970-01-01
  • 1970-01-01
  • 2018-09-18
相关资源
最近更新 更多