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

more articles to enjoy:

passing command-line parameters to imagej
11 october 2013 | programming

The processes of passing command-line parameters to ImageJ plugins isn't the most direct. Illustrated is a simple solution to this problem,[...] full code included.

the evolving style
29 march 2012 | design

This website was built from scratch using only Notepad. While it would have been easier to create the site in Dreamweaver or another pr[...]ogram and then upload it, I wanted to learn first-hand about the steps involved in web development. The site has allowed me to hone my design skills, both aesthetically and organizationally. This is an essay detailing the evolution of the website.

This was an internal document for me to keep track of what I was changing and why, but decided to reword it and make it an article. Hope you like it.

week 1 | go time
12 june 2012 | singapore

Wow, what a week. Ran around Hong Kong, learned a couple new things in the lab, meet a bunch of awesome MIT/SUTD students, went clubbing tw[...]ice, ate a different type (Indian, Indonesian, Muslim, etc.) of food each meal, wandered around Singapore several of the nights and so much more. To top it all off, I was able to learn a ton about Singapore's culture. This place is awesome.

dreams
02 july 2012 | essay

I have been recording down many recent and very old dreams in a Word document, which has swelled to over 7,000+ words and contains near one[...] hundred stories. The plan is to clean-up and compile all these stories into one novella that has several characters exploring the dream-worlds with some overarching story to tie it all together. Should be a fun experiment.

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