Commanding Chaos for Coworking, Open Source and Creative Communities

awk magic: renaming batch files

Wed, 08/13/2008 - 07: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.