Home > Software design >  shell find - get folder name for current file
shell find - get folder name for current file

Time:11-18

I want to use exiftool to give serial numbers to jpg-files. The files are contained in sub directories to a main directory What can I replace FOLDER_OF_CURRENT_FILE with to achieve this?

find . -type f -name "*.jpg" -exec exiftool -SerialNumber=FOLDER_OF_CURRENT_FILE;

CodePudding user response:

With find:

find . -mindepth 2 -type f \( -iname '*.jpg' -o -iname '*.jpeg' \) \
-exec sh -c '
    for path do
        dir=${path%/*}
        dir=${dir##*/}
        echo exiftool -overwrite_original -SerialNumber="${dir}" "$path"
    done' _ {}  

This is a dry run. You can run it, and view the command line to be executed. If it looks ok, remove echo to run for real.

  • -mindepth 2 must specified, unless you want -SerialNumber=.
  • -iname means ignore case

Alternatively, it's possible to do this entirely with exiftool:

exiftool -r -overwrite_original '-SerialNumber<${directory; s=.*/==s;}' .
  • -r is for recursive
  • Exiftool allows attributes to be specified, and arbitrary perl code to be injected with them. So perl substitution can be used to remove everything up to the last directory. I used the s modifier (second s) to cover paths which might contain a new line.
  • There's also ${directory;my @a=split m(/); $_ = $a[-1]} which produces the same result (split path by slash in to an array, and use the last element)
  • This modifies all supported file formats. To specify jpg files only, replace . with -ext jpg -ext jpeg .
  • Obviously, -overwrite_original is optional, but running recursively might create many duplicate images otherwise
  • Related