bash脚本 - 重命名包含* space *()*的目录中的所有文件

时间:2016-08-12 09:26:32

标签: windows bash cygwin sh

我在这里没有选择..

我在这里看了很多关于这个主题的帖子,但由于某些原因,这些答案对我没有用。

我想要一个简单的脚本将给定文件夹中的所有文件重命名为任何内容!说一个柜台nr。即:

  

1.JPG

     

2.pdf

     

3.exe

我的部分脚本需要这个,因为我无法移动文件,因为它们有特殊的字符:

我在 win7 计算机上使用 cygwin ,文件是从 win7 创建的,例如:

test01.jpg
test01 (2).jpg
test01 (2) - Copy.jpg

这是脚本的一部分,我需要它才能使它工作:

pathF="d:/scripts/img/_sandbox/depFrom"
searchAll=$(find $pathF -type f | egrep ".*")
ct=0
for fAll in $searchAll; do
    # echo -e $fAll
    # echo -e "$ct"
    old=$fAll
    # new=$(sed "s/\ //g" $fAll)
    mv -v $old $ct #$new
    ((ct++))
done

在这个例子中我只想处理空格,但我需要处理() - 和空格来覆盖所有。

这是我的控制台中的输出: output 出于某种原因,它似乎在延伸之间和之后的空间停止/分裂。

非常感谢任何帮助。

=============================================== ===================

修改 我试过这个:

pathF="d:/scripts/img/_sandbox/depFrom"
searchAll=$(find $pathF -type f -printf "%f\n")
for fAll in $searchAll; do
    echo -e $fAll
done

输出是这样的:

test01
(2)
-
Copy.jpg

文件夹中只有一个文件!!

$ ls depFrom/
test01 (2) - Copy.jpg

$ find depFrom/ -type f -printf "%f\n"
test01 (2) - Copy.jpg

2 个答案:

答案 0 :(得分:1)

问题已经出现在find的输出中。任何空间都被认为是由它后面的命令分隔。您应该使用选项

   -print0
          True; print the full file name on the standard output, followed by a null character
          (instead  of  the newline character that -print uses).  This allows file names that
          contain newlines or other types of white space to be correctly interpreted by  pro‐
          grams  that  process  the find output.  This option corresponds to the -0 option of
          xargs.

此外,在使用文件名时应使用正确的撇号 可以包含空格

mv -v "$old" "$ct"

答案 1 :(得分:1)

只要文件名不包含换行符,这就应该有效。

pathF="d:/scripts/img/_sandbox/depFrom"
counter=0
find "$pathF" -type f | while read f; do
    mv "$f" "$((++counter))${f/*\./.}" #increment counter, preserve extension
done

如果您不需要递归搜索pathF,那么如果您从我的答案中添加扩展保留代码,那么在原始问题下的123评论中提供的解决方案应该适合您:

x=0;for i in *;do mv "$i" "$((++x))${i/*\./.}";done