Mike Fleming
Mike Fleming

Reputation: 2673

Rename files to new naming convention in bash

I have a directory of files with names formatted like

[email protected]
[email protected]
[email protected]

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

Upvotes: 0

Views: 94

Answers (2)

Ed Morton
Ed Morton

Reputation: 203674

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

Upvotes: 3

Alexandre Juma
Alexandre Juma

Reputation: 3313

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 [email protected] PETERSON.png
mv [email protected] BRADLEY.png
mv [email protected] JACOBS.png
mv [email protected] MATTS.png
mv [email protected] JACKSON.png

Upvotes: 2

Related Questions