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

other entires to explore:

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.

comment system!
05 august 2012 | website

Wanted to add the ability for people to comment on this website, but delayed adding the feature until I could write the code myself. There [...]are many pre-built PHP solutions on the market (like commentator), but the original purpose of this site was to allow me to learn how to build a website from scratch. So I've implemented the comment system using about a hundred lines of code to access the MySQL database, verify inputs and display all the comments for a particular article.

wary statistics #1: the tale of cdc mortality
06 april 2020 | statistics

I will briefly discuss properly interpreting data you might see in the mainstream or on social media. The takeaway: if recent data for some[...] measure (e.g. pneumonia deaths) from this year looks to be different than prior years, make sure to check that it is not an artifact of data collection or compilation.

from the archives: declaration of independence, internet edition
11 july 2013 | america

A revised Declaration of Independence I did awhile ago (i.e. high school) for a writing class. It is slightly a mockery of the style of wri[...]ting sometimes used back then, e.g. finding unnecessarily complicated ways of saying a simple concept; long, ponderous sentences; and an abuse of the Capital.

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