Dup Ver Goto 📝

HashRename

PT2/shell/nu/examples does not exist
To
25 lines, 143 words, 730 chars Page 'HashRename' does not exist.

When organising things like images and trying to avoid duplicates, one pattern is to rename everything to dirname_deadbeef0123.ext where the deadbeef0123 is the first 12 hex digits of the sha256 sum.

In nushell this becomes

def hash_rename [
  stem = ""
  ] {
  let s = ( if $stem == "" { pwd | path basename } else { $stem } )
  let xs = $in
  if ( $xs | is-empty ) { ls *.* } else { $xs } | each { |x|
    let ifn = $x.name
    let ext = ( echo $ifn | path parse | get extension )
    let hash = ( sha256sum $ifn | str substring 0..11 )
    let ofn = $"($s)_($hash).($ext)"
    if ( $ofn | path exists ) {
      print $"($ofn) exists"
    } else {
      print $"($ifn) to ($ofn)"
      mv -v $ifn $ofn
    }
  }
}