递归重命名文件,以ASCII标准 [英] Recursively rename files to ASCII Standard

查看:164
本文介绍了递归重命名文件,以ASCII标准的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此​​,我们必须在这里我们需要通过成千上万的图像抓取,并重新命名他们都符合标准ASCII码的一个问题。做了很多研究网上之后,我们发现这个方便的一块code的:

  MV'文件'$(回声文件| sed的-e的/ [^ A-ZA-Z0-9 ._-] / _ / G')

从来源:如何从文件名 <删除无效字符/ p>

我已经尝试过合并为一个递归find命令,将在我们的主要images目录中,同时运行:

 找到。 -print0 | xargs的-0 MV $(回声| sed的-e的/ [^ A-ZA-Z0-9 ._-] / _ / G')

但我似乎无法得到它的运行。我已经得到最接近的,是上面code扔了很多的MV:目标文件名不是目录

因此​​,谁能帮助这个?


解决方案

我想这会更好:

 找到。型的F -exec的bash -c'为f执行D = $ {F%/ *} B = $列{F ## * /} NB = $ {B // [^ A-ZA-Z0-9 ._-] / _}; [[$ B =$ NB]] ||回声MV$ F,$ D / $ NB;做'_ {} +

找到将找到的所有文件(型的F ),将它们作为位置参数这一击片段:

 为f执行
    D = $ {F%/ *} B = $列{F ## * /} NB = $ {B // [^ A-ZA-Z0-9 ._-] / _}
    [[$ B =$ NB]] ||回声MV$ F,$ D / $ NB
DONE

我们分裂了文件名,目录名 D 和基名 B 。我们使用参数扩展用下划线替换所有不想要的字符并保存扩展到变量 NB 。我们检查扩展 $ B $ NB 是不同的(从而避免错误与 MV ),如果它们是不同的,进行重命名。

我离开回声所以,没有什么实际执行的命令仅回应。删除回声如果它看起来不错。

请注意,这将会覆盖一些文件,例如,文件 A&安培; B a_b

So we have a problem where we need to crawl through hundreds of thousands of images and rename all of them to comply with ASCII standards. After doing a lot of research online, we found this handy piece of code:

mv 'file' $(echo 'file' | sed -e 's/[^A-Za-z0-9._-]/_/g')

sourced from: How to remove invalid characters from filenames

I have tried merging it into a recursive find command, to be run whilst in our main images directory:

find . -print0 | xargs -0 mv $(echo | sed -e 's/[^A-Za-z0-9._-]/_/g')

But i cant seem to get it to run. The closest i've gotten, is the above code throwing a lot of "mv: target filename Is not a directory"

So can anyone help with this ?

解决方案

I guess this would be better:

find . -type f -exec bash -c 'for f do d=${f%/*} b=${f##*/} nb=${b//[^A-Za-z0-9._-]/_}; [[ $b = "$nb" ]] || echo mv "$f" "$d/$nb"; done' _ {} +

find will find all files (-type f), pass them as positional arguments to this Bash snippet:

for f do
    d=${f%/*} b=${f##*/} nb=${b//[^A-Za-z0-9._-]/_}
    [[ $b = "$nb" ]] || echo mv "$f" "$d/$nb"
done

We split the filename into dirname d and basename b. We use parameter expansions to replace all the unwanted characters with underscores and save that expansion into variable nb. We check that the expansions $b and $nb are distinct (so as to avoid an error with mv), and if they are distinct, perform the renaming.

I left echo so that nothing is actually performed, the commands are only echoed. Remove the echo if it looks good.

Note that this can overwrite files, e.g., files a&b and a_b.

这篇关于递归重命名文件,以ASCII标准的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆