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:

bash scripting: batch file renamer
25 february 2013 | programming

Bit by bit, I have replaced repetitive tasks completed using downloaded programs with scripts that do the same thing more efficiently, with[...]out the residual registry and file junk many programs leave, and with the flexibility to allow me to modify the script to suite specific needs in the future. This was the case with batch renaming files. I've included the script and briefly go over the code.

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.

graduate student resources
19 august 2015 | graduate school

Providing links to some articles and other resources that I have found useful while in graduate school. I'll continually update the list as[...] I find more.

¿qué es la calle?
24 may 2013 | short story | spanish

Había terminado y salé para mi cocina. Tenía hambre pero este día no había comida dentro de mi despensa. Me fui y caminé hacienda[...] la Tport—una máquina que puede transportar una persona a otro lugar sin energía y tiempo. Cuando entré la máquina, toqué algunos botónes y esperé. Pero nada ocurrió y lo hice las mismas acciones otra vez—y nada ocurrió.

How would the disappearance of streets affect the social fabric? This short story briefly (in castellano!) explores a world in which instantaneous, free transport is possible. Meant mainly to practice my spanish, i plan to follow-up with a more detail story in the future.

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