bash scripting: randomly rename files

Summary

Small script to enable quick randomization of files in a directory and conversion back to original names later. Original inspiration was a way to blind data analysis, e.g. if studying images from an experiment and don't want to be biased by the conditions applied.

Small script to enable quick randomization of files in a directory and conversion back to original names later. Original inspiration was a way to blind data analysis, e.g. if studying images from an experiment and don't want to be biased by the conditions applied.

The script is commented and pretty self-explanatory, so i won't spend time going over it---see below for the script and download. It include the ability to input specific directories, wasn't going to add it at first, but might as well have the feature. One neat trick is using usrDir=`cd $2; pwd`/ to get the absolute path from a users relative path. Yes, i decided to use getopts this time. Other than that, pretty standard fare. Enjoy!

download the script
Bash
  1. # !/bin/bash
  2. # biafra ahanonu
  3. # updated: 2013.06.14
  4. # randomly rename files in directory and convert back when needed; the extensions of the files are conserved during the change.
  5.  
  6. #TODO:
  7.         # add option (-i) to hide output
  8.         # allow regexp option (-r) via sed filter or other to allow only particular files to be chosen
  9.         # test with foreign characters (e.g. é, ñ, etc.)
  10.  
  11. #Reset if getopts was used previously
  12. OPTIND=1
  13.  
  14. getArgs(){
  15.         # branches script based on input options
  16.         # list of options, colon signifies options that should have an argument after
  17.         optionsCheck=":hd:e:"
  18.         # if no input...
  19.         if [[ -z $1 ]]; then
  20.                 echo "Please enter an argument"
  21.                 separator
  22.                 viewHelp
  23.                 exit 0
  24.         fi
  25.         # check if directory set, else use local folder
  26.         # ${!#}
  27.         if [ -z "$3" ]; then
  28.                 usrDir="./"
  29.         elif [[ $3 ]]; then
  30.                 usrDir=$3
  31.         fi
  32.         # branch based on options
  33.         while getopts $optionsCheck opt; do
  34.                 case "$opt" in
  35.                         h|\?)
  36.                                 viewHelp
  37.                                 exit 0
  38.                                 ;;
  39.                         e)
  40.                                 logfile=$OPTARG
  41.                                 encode $logfile $usrDir
  42.                                 ;;
  43.                         d)
  44.                                 logfile=$OPTARG
  45.                                 decode $logfile $usrDir
  46.                                 ;;     
  47.                         *)
  48.                                 echo "Please enter an argument"
  49.                                 exit 0
  50.                                 ;;             
  51.                 esac
  52.         done
  53.         # shift off the options and optional --.
  54.         shift $((OPTIND-1))
  55. }
  56. viewHelp(){
  57.         # help documents, called in getArgs
  58.         echo -e 'file hasher v1.0 by biafra ahanonu\n'
  59.         echo -e 'randomize.sh -options [DIRECTORY]\n'
  60.         echo 'DIRECTORY defaults to ./ (current dir) unless specified. Full paths are stored in log file.'
  61.         echo 'OPTIONS'
  62.         echo -e '\t-e [file] : randomly renames DIRECTORY files and stores hash in [file]'
  63.         echo -e '\t-d [file] : reads hashes from [file] and renames DIRECTORY files accordingly'
  64.         echo -e '\t-h/-help : displays help (little catch-22)'
  65. }
  66. encode(){
  67.         # randomize files inside a folder and store log in above folder
  68.         # Get absolute path to improve later decoding
  69.         usrDir=`cd $2; pwd`/
  70.         # !clear/create new log file
  71.         logfile=$usrDir$1;rm $logfile;touch $logfile
  72.         echo 'encoding files...log is '$logfile
  73.         # get extension and base for log file
  74.         ext=${logfile##*.};fbname=${logfile%.*}
  75.         # loop over each file, get random number and rename
  76.         separator
  77.         for oldFile in $( find $usrDir -maxdepth 1 -type f ); do
  78.                 if [[ "$oldFile" == *"$logfile"* ]]; then
  79.                         continue
  80.                 fi
  81.                 # get old file extension to preserve
  82.                 ext=${oldFile##*.}
  83.                 # use $RANDOM to generate random, extension preserved filename
  84.                 randomFile="$usrDir$RANDOM"."$ext"
  85.                 # ...
  86.                 mv $oldFile $randomFile
  87.                 # mv $oldFile oldfiles/$oldFile
  88.                 echo -e $oldFile"\t"$randomFile >> $logfile
  89.                 echo $oldFile -\> $randomFile
  90.         done
  91.         separator
  92.         echo "-encoding finished, log stored in $logfile"
  93.         echo "-to decode, type: randomize.sh -d $logfile"
  94. }
  95. decode(){
  96.         # convert files in the log back to their original form
  97.         echo 'decoding files from '$2$1
  98.         logfile=$2$1
  99.         # read each line of log, print out conversion then pass a mv command to system
  100.         separator
  101.         gawk '{print $2" -> "$1; system("mv "$2" "$1)}' $logfile
  102.         separator
  103.         echo 'Decoded files!'
  104. }
  105. separator(){
  106.         # standardize separator output...
  107.         echo "---------------------"
  108. }
  109. #run script
  110. getArgs $@

-biafra
bahanonu [at] alum.mit.edu

additional articles to journey through:

quicklinks github
12 august 2012 | programming

quicklinks is a new homepage for those looking for efficiency over lavish use of big buttons commonly seen in Firefox, Opera and other brow[...]ser's homepages. As quicklinks is still a little rough around the edges and needs to be updated, I've added it to GitHub to allow me to update it easier.

bio42: notes
12 may 2013 | teaching

While teaching bio42 (cell biology and animal physiology) I created weekly notes to help students in my section study and focus on the impo[...]rtant materials presented in the class. I built off of the latex boilerplate that I have been improving over time to create weekly notes. This highlights why I love LaTeX so much, especially for larger projects that are heavily linked—it allows easy annotation, indexing, creation of new document styles, and other related processes rapidly and consistently. Plus, separating content and style is always a plus and images stay uncoupled from a propriety source (e.g. Word files).

I really love the resulting notes and student feedback was quite positive. I thought sharing them might be useful for others in the future. The source latex files and raw images can be sent upon request (I'm considering making a Github repository in the future). I'll briefly talk about the document below and certain decisions that were made to get it to its current state.

archive everything!
01 october 2012 | notes

Archived everything in my inbox. It's awesome. Continues my general trend of simplifying. Logging off websites, only checking the news for [...]brief periods, and focusing on a core set of hobbies. Eliminating distractions and reducing information overload are doing wonders to fight off stress and keep me humming along.

week 1 | flying out
09 june 2012 | singapore

I fly out to Singapore today. Two days, 11,459 miles and (hopefully) one A Song of Fire and Ice book later, I'll be in my dream city. Can't[...] wait!

©2006-2024 | Site created & coded by Biafra Ahanonu | Updated 17 April 2024
biafra ahanonu