Home > Net >  Randomly shuffling all files in a directory?
Randomly shuffling all files in a directory?

Time:04-30

I am trying to find a solution with bash to shuffle a directory full of 2x3000 files of the type:

.mp4

.json (stores the metadata).

The .mp4 and .json are connected to each other so, the problem is:

I can shuffle both individually, but this loses the indirect connection in the process. So I would need a code, which stores the random value, into a variable and assign it to my .mp4 json package each.

The folder contains

  • 1.mp4
  • 2.mp4
  • 3.mp4
  • 3000.mp4

and also

  • 1.json
  • 2.json
  • 3.json
  • 3000.json

I´ve looked everywhere on the platform but didnt find a satisfying solution and its beyond my bash skills!

This was my base code:

for i in *; do mv "$i" $RANDOM-"$i"; done

paste <(printf "%s\n" *) <(printf "%s\n" * | shuf) |
  while IFS=$'\t' read -r from to; do mv -- "$from" "$to.mp4"; done

for f in *.mp4; do mv -- "$f" "${f%.mp4}"; done 

Thank you!

cheers Michael Schuller

CodePudding user response:

You can do it like that:

#!/bin/bash

find . -type f -name "*.mp4" -print0 | while IFS= read -r -d '' file
do
    # Remove prefix ./
    filenoprefix="${file#./}"
    # Remove extension
    filenoext="${filenoprefix%.*}"
    # New name is random-oldfilename
    newfilename="$RANDOM-$filenoext"
    # Rename files .mp4 and .json
    mv "$filenoext".mp4 "$newfilename".mp4 && mv "$filenoext".json "$newfilename".json
done
  • the find ... | while is from https://mywiki.wooledge.org/BashFAQ/001
  • variable substitution is used to remove the ./ prefix find adds to results.
  • the extension is removed from the filename
  • the new filename is a concatenation of $RANDOM and the original filename
  • and finally, 2 mv commands separated by &&.

Note: this works ok if you run the script in the same directory as where the files are.

Note 2: this works ok if all files are in the same directory. I did not make it general since you mentioned that all files are in the same directory anyway.

CodePudding user response:

I found some help in the ubuntu discord!

Here is the solution

for i in *.mp4; do
  noext="${i%.*}";
  newname="$RANDOM";
  mv "${noext}.json" "${newname}-${noext}.json";
  mv "${noext}.mp4" "${newname}-${noext}.mp4";
done
  • Related