1

Assuming an arbitrary number of files with random names and the same file extension (e.g., file1.txt, file2.txt...fileN.txt). How could you rename them all reliably with a random string?

Such as, file1.txt, file2.txt...fileN.txt to asdfwefer.txt, jsdafjk.txt... or any combination of letters from latin alphabet].txt

3
  • 1
    Just a simple iteration and rename? Why is complex? What is your attempt? Commented May 7, 2022 at 17:02
  • @JRichardsz for file in *.txt; do mv -- "$file" "${file%.txt}[random string].jpg" done I don't know how to introduce the random string Commented May 7, 2022 at 17:20
  • Does this answer your question? Using "$RANDOM" to generate a random string in Bash Commented May 7, 2022 at 18:30

2 Answers 2

2

These are the algorithm steps:

  • iterate files
  • get name and extension
  • compute a random string
  • rename using mv command

script.sh

location=$1

echo "before"
find $location

for full_file_name in $location/*.*
do
    filename=$(basename -- "$full_file_name")
    extension="${filename##*.}"
    filename="${filename%.*}"
    new_name=$(cat /dev/urandom | tr -dc 'a-z' | fold -w 32 | head -n 1)
    echo "rename from: $filename.$extension to: $new_name.$extension"
    mv $full_file_name "$location/$new_name.$extension"
done

echo "after"
find $location

execution

bash script.sh /tmp/workspace/input

result

Script was tested and the result of demo files is here

Sign up to request clarification or add additional context in comments.

3 Comments

A screen shot of the output is less useful than just a copy/paste of the actual text. Please don’t post images of code, error messages, or other textual data.
I think this may help the reader believe that the algorithm works because is an image as proof. Also the images prohibition is commonly for questions, not for the answers and only for source code or error messages. Thanks for the feedback.
Images have multiple usability problems which are spelled out in the link I provided. If we really thought you wanted to falsify information in your answer, a forged image is not much harder to produce than forged text.
1

quickest hack to get a random-letters string I can think of is

head -c24 /dev/urandom | base64 | tr -dc a-zA-Z

so

randomname() { head -c24 /dev/urandom | base64 | tr -dc a-zA-Z; }
for f in file*.txt; do mv "$f" `randomname`.txt; done

and your odds of a collision are down in the one-in-a-billion range even with a huge list. Add a serial number on the end of randomname's output and that goes away too.

Comments