Commanding Chaos for Coworking, Open Source and Creative Communities

awk magic: renaming batch files

Wed, 08/13/2008 - 04:46 -- rprice

Hmm, somehow, files that should be jpegs have the extension ".null"... ugly!

ls -1 | \
awk -F\. '/.null/ { print "mv " $0, $1".jpg" }' \
| bash

Let's say you have a bunch of files named "image.jpg.jpg"... ugh!

rprice@server$ ls -1 | \
awk -F\. '/.jpg.jpg/ { print "mv " $0, $1"." $2 }' \
| bash

Now they are renamed to just "image.jpg", that's pretty simple

Next challenge: you have several images which are named "image(1).jpg"... what do you do?

rprice@server$ ls -1 *\(1\)* | \
awk -F '\(1\)' '{ print "mv "$0 "(" $1 "" $2 "" $3 "" $4}' | \
awk -F\( '{ print $1 "\\(" $2 ")" $3 "" $4 "" $5}' | \
awk -F\) '{ print $1 "\\)" $2 " " $3 "" $4 "" $5}' \
| bash

Now they are also renamed to just "image.jpg" - you are a winner!

...and if you had anything named "image.jpg(1).jpg", you will have to run both of these scripts. Lucky you!

For more awk tutorials, check out Drupal Easy.

P.S. if you also have a database that has the same nasty file names like this in it, example:
34,135887,image with spaces,image_with_spaces.jpg(1).jpg,image/jpeg,1
export the thing as a CSV and then apply the following script to the file before you drop all the rows and put them back in:

awk -F, 'BEGIN { OFS = "," } {
sub(/\([0-9]\)/, "", $4)
sub(/\.jpg\.jpg/, ".jpg", $4)
split($4, arr, "/")
print $1, $2, arr[2], "files/legacy/" $4, $5, $6
}' files.csv

Categories: 

Commenting on this Blog post is closed.

Comments

Submitted by Michael Grant (not verified) on

It's past time to move away from AWK.

Don't get me wrong, I've used AWK. Hell, between friends of mine, we've lived AWK.

But Perl (and even BASH shell scripting) -- you don't need awk.

> for FILE in `ls *`
do
mv $FILE $FILE.jpg
done

> for FILE in `ls *.jpg*.jpg`
do
mv $FILE ${FILE%*.jpg}
done