Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash script to prepend a random number to all files

Tags:

linux

bash

I have a "smart" phone that doesn't seem to have a music shuffle function, so the next best thing is to write a bash script to prepend all filenames in the current directory with a random number.

Is this difficult to do?

like image 266
Reinderien Avatar asked Jul 04 '10 16:07

Reinderien


2 Answers

No, this is not hard to do. It will however mess up your carefully crafted filenames, and might be hard to undo.

You can use $RANDOM as a simple source of random numbers in bash. For your case:

#!/bin/bash
for file in *; do
  mv "$file" $RANDOM-"$file"
done

I didn't test this. You probably want to test this yourself on some small sample to make sure you know what it does.

like image 189
Benjamin Bannier Avatar answered Sep 18 '22 02:09

Benjamin Bannier


This script will shuffle files and reshuffle them if they've already been shuffled. If you pass it an argument of -u it will unshuffle the files (remove the random prefix).

#!/bin/bash
for file in *.mp3
do
    if [[ -d $file ]]
    then
        continue    # skip directories
    fi
    if [[ $file =~ ^1[0-9]{5}9-(.*).mp3$ ]]    # get basename
    then
        name=${BASH_REMATCH[1]}                # of a previously shuffled file
    else
        name=${file%.mp3}                      # of an unshuffled file
    fi
    if [[ $1 != -u ]]
    then
        mv "$file" "1$(printf "%05d" $RANDOM)9-$name.mp3"    # shuffle
    else
        if [[ ! -e "$file.mp3" ]]
        then
            mv "$file" "$name.mp3"                           # unshuffle
        fi
    fi
done

It uses a fixed-width five digit random number after a "1" and followed by "9-" so the shuffled filenames are of the form: 1ddddd9-filename maybe with spaces - and other stuff.1983.mp3.

If you re-run the script, it will reshuffle the files by changing the random number in the prefix.

The -u argument will remove the 1ddddd9- prefix.

The script requires Bash >= version 3.2.

like image 41
Dennis Williamson Avatar answered Sep 21 '22 02:09

Dennis Williamson