以递归方式删除文件名和文件夹之前的空格

时间:2016-10-19 14:40:44

标签: bash unix

我正在将内容从旧的xServe移动到Synology NAS,并且客户在10年前决定在文件名和文件夹之前添加一个或多个空格,以使它们在树中显得更高。 将所有内容移至Synology NAS时,我们会因此而遇到很多错误。

对我来说,理想的解决方案是使用一个脚本只删除名称前面的空格并保留其余部分。

我找到了另一个类似的线程here但是删除了任何空格,无论它在名称中的位置如何。另一个帖子的脚本是

find /tmp/ -depth -name "* *" -execdir rename 's/ /_/g' "{}" \;

有没有人有想法?

谢谢!

3 个答案:

答案 0 :(得分:1)

这应该按照你的要求做。

for oldname in /path/to/directory/* 
do
    newname="$(echo $oldname | sed 's/^ //')"
    #echo 'mv' "${oldname}" "${newname/ /}" ## Uncomment this line to test 
    mv "${oldname}" "${newname/ /}"
done

答案 1 :(得分:1)

Thank you for helping out. With the help of Jean-Baptiste Yunès I managed to get this command that works perfectly. Thanks for all your help!

find /your-folder/ -depth -name "* *" -execdir rename 's/^ *//' "{}" \;

答案 2 :(得分:0)

Something like that should do the trick:

for i in "/path/to/directory with spaces/"* ; do
    dirname="$(dirname "$i")" # replace with the hardcoded path if you want
    newname="$(echo "$i" | sed "s|$dirname/ \+|$dirname/|")"
    # redirect to /dev/null if there are collisions or files without leading spaces
    mv "$i" "$newname" 2>/dev/null
done

You could write it as oneliner, but then it looks somehow messy with ". I suggest wrapping into a script with replacing the directory with $1.