简体   繁体   中英

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. What is the best way to go about this?

Edit: my bash version is 3.2.57(1)-release

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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