Tuesday, September 24, 2013

Dynamically altering filenames in a for loop using bash

So I had to move a couple of #flightgear screenshots around on my system, and came up with a oneliner to do it.

And of course, #bash, as always, fails horribly with spaces-in-filenames. So this one won't work if there are spaces.

for x in $(locate --regex "fgfs-screen-...\.png")
# in a subshell, execute a search to find the following files:
## any file beginning with fgfs-screen-
## followed by three of any characters
## followed by .png
# then, for each iteration of the loop, store the list element to $x
  do echo $x
# print the filename to the terminal
y=`stat -c %Y %x
# store the time of last modifcation, seconds since Epoch to $y
z=`basename $x`
# strip the directory path and store it to $z
mv -v "$x" "$z{%-*}-$y.png"
# move the original file to a new file with:
## in the current directory,
## everything with the basename stripped after the final -
## adding the epoch timestamp and file extension
done
# finish for loop


  



the results of this endeavor are viewable here: http://imgur.com/a/dkOu4#0