Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

The task is to replace a file's (actually of all the files in a directory) name (but leave extension intact) with a random UUID/GUID. Any ideas on how to do this?

share|improve this question

3 Answers 3

Similar to bahamat answer, but generates actual UUIDs. UUIDs have some reserved bits that are used to determine the version and variant used. There are currently 5 types of UUIDs defined, random UUIDs, as you asked, are version 4. You will note that version 4 UUIDs have this format:

442b7f35-f33f-4b8d-9a07-db8ec207129e
              |    '-- variant (bits 10__ -> [89AB])
              '------- version (bits 0100 -> 4)

Also, this version doesn't cause damage in case the UUID generation fails.

for i in *; do uuid=$(uuidgen -r) && mv -- "$i" "$uuid.${i##*.}" done

Using /proc/sys/kernel/random/uuid:

for i in *; do uuid=$(cat /proc/sys/kernel/random/uuid) && mv -- "$i" "$uuid.${i##*.}" done
share|improve this answer

Something like this:

for i in *; do mv -- "$i" "$(openssl rand -hex 16).${i##*.}"; done

Using openssl rand 16 gives you 128 bit GUIDs. Use 32 if you want 256 bit GUIDs.

share|improve this answer
3  
If you have it, uuidgen works too (sys-apps/util-linux in Gentoo) –  Michael Mrozek Jan 18 '11 at 3:39
1  
UUIDs are not completely random. Random UUIDs are version 4 UUIDs, and have only 122 random bits, not 128. The fixed bits define the version (4) and variant of the UUID. You should use either uuidgen or /proc/sys/kernel/random/uuid to generate UUIDs. –  Juliano Jan 19 '11 at 0:18

Short Perl script below - the use of cat to get the uuid isn't the cleanest/fastest way to code it, but it keeps the command short:

perl -e '
  foreach (@ARGV) {
    my $uid=qx|cat /proc/sys/kernel/random/uuid|;
    chomp $uid;
    (my $new=$_)=~s#(.*)\.#$uid.#;
    rename($_, $new)
  }
' *.file_ext

The above uses a file in /proc on linux as a source of uuids:

[bash#] cat /proc/sys/kernel/random/uuid
d474706f-b18c-4e4b-8762-5ed577c74ac3
share|improve this answer
1  
ls output is not meant to be parsed. ls is meant to produce user-readable output, and it may substitute characters in filenames. –  Juliano Jan 19 '11 at 0:25
    
@Juliano Point taken - but using a shell glob "*.file_ext" risks an "argument list too long error", whereas the error risks from "\ls -1 | pipeline..." are minimal - it's a more pragmatic solution. –  frielp Jan 19 '11 at 8:58

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.