jump to navigation

awk magic: renaming batch files August 13, 2008

Posted by Ryan in : Tech, , , , trackback

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

Comments»

1. Michael Grant - October 13, 2008

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


- Why ask? This confirms you are a human user!

Why ask?

Why ask?