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: youtube downloading macro
17 may 2013 | programming

<p> Once again, the command line is the root of all that is good in the world. This time, it has helped improve on a long[...]-standing issue for me: what is the easiest way to get a copy of all the <a href='http://www.youtube.com/playlist?list=PLmku2swCXQpqWAZSscjV4h9bcLennVcif' target='_blank'>luscious melodies</a> i hear on youtube? Courtesy of <a href='http://rg3.github.io/youtube-dl/' target='_blank'>youtube-dl</a>, a nifty little command line utility, this problem has been solved. However, every once in awhile it throws errors and i wanted a wrapper bash script to take care of this and some other processing. I'll briefly go over the code. </p>

55 fiction
02 march 2006 | short story

Collection of three short pieces of fiction that contain only fifty-five words. They are all play on words.[...]

movie review: star wars the force awakens
21 december 2015 | movies

Star Wars: The Force Awakens is an okay movie when viewed through the eyes of an adult, but is a fun, entertaining movie if you go in with [...]a twelve year old's mindset. It pushes the right buttons and has a good amount of fan service. But it ultimately fails as a standalone movie—with its boring/predictable plot, rehashed characters and concepts, and other flaws—that will ultimately be remembered as good or bad depending on how episodes VIII and IX turn out.

stanford bing concert hall: first impressions
15 december 2012 | stanford

Designed by architect Richard Olcott (Ennead Architects) and sound designer Dr. Yasuhisa T[...]oyota (Nagata Acoustics), the Bing Concert Hall is stunning. Robert Campbell (Fisher Dachs Associates) was on hand during the second sound check (along with Richard and Dr. Toyota) to discuss the philosophy behind the building, a bit of history, and where they hope it will be in the future. This post is my impressions of the place along with notes from their interview.

©2006-2025 | Site created & coded by Biafra Ahanonu | Updated 21 October 2024
biafra ahanonu