简体   繁体   English

将文件重命名为bash中的新命名约定

[英]Rename files to new naming convention in bash

I have a directory of files with names formatted like 我有一个文件目录,其名称格式如下

01-Peterson@2x.png
15-Consolidated@2x.png
03-Brady@2x.png

And I would like to format them like 我想格式化它们像

PETERSON.png
CONSOLIDATED.png
BRADY.png

But my bash scripting skills are pretty weak right now. 但是我的bash脚本编写技能现在很薄弱。 What is the best way to go about this? 最好的方法是什么?

Edit: my bash version is 3.2.57(1)-release 编辑:我的bash版本是3.2.57(1)-发行版

If the pattern for all your files are like the one you posted, I'd say you can do something as simple as running this on your directory: 如果您所有文件的模式都类似于您发布的模式,那么您可以执行以下操作,就像在目录中运行该命令一样简单:

for file in `ls *.png`; do new_file=`echo $file | awk -F"-" '{print $2}' | awk -F"@" '{n=split($2,a,"."); print toupper($1) "." a[2]}'`; mv $file $new_file; done

If you fancy learning other solutions, like regexes, you can also do: 如果您想学习其他解决方案(例如正则表达式),也可以执行以下操作:

for file in `ls *.png`; do new_file=`echo $file | sed "s/.*-//g;s/@.*\././g" | tr '[:lower:]' '[:upper:]'`; mv $file $new_file; done 

Testing it, it does for example: 测试它,例如:

mv 01-Peterson@2x.png PETERSON.png
mv 02-Bradley@2x.png BRADLEY.png
mv 03-Jacobs@2x.png JACOBS.png
mv 04-Matts@1x.png MATTS.png
mv 05-Jackson@4x.png JACKSON.png

This will work for files that contains spaces (including newlines), backslashes, or any other character, including globbing chars that could cause a false match on other files in the directory, and it won't remove your home file system given a particularly undesirable file name! 这将适用于包含空格(包括换行符),反斜杠或任何其他字符(包括通配符)的文件,这些字符可能会导致目录中其他文件的错误匹配,并且由于特别令人讨厌的原因,它不会删除您的主文件系统文档名称!

for old in *.png; do
    new=$(
        awk 'BEGIN {
                base = sfx = ARGV[1]
                sub(/^.*\./,"",sfx)
                sub(/^[^-]+-/,"",base)
                sub(/@[^@.]+\.[^.]+$/,"",base)
                print toupper(base) "." sfx
                exit
            }' "$old"
        ) &&
    mv -- "$old" "$new"
done

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM