POSIX alternative to GNU find’s -printf predicate

findportabilityposixprintf

I'd like to rewrite these 2 commands so they will use only POSIX-compliant switches:

find "$TARGET_DIR" -maxdepth 1 -type d -printf '(DIR)  %f\n'
find "$TARGET_DIR" -maxdepth 1 -type f -printf '%s  %f  ' -exec file -b {} \;

-maxdepth 1 can probably be replaced with -prune, but -printf will require a more complicated redirection.

Best Answer

Try:

find "$TARGET_DIR//." \( -name . -o -prune \) -type d -exec sh -c '
  for f do
    f=${f%//.}
    f=${f%"${f##*[!/]}"}
    f=${f##*/}
    printf "(DIR) %s\n" "${f:-/}"
  done' sh {} +

It would be simpler for the equivalent of -mindepth 1 -maxdepth 1:

find "$TARGET_DIR//." \( -name . -o -prune \) -type d -exec sh -c '
  for f do
    printf "(DIR) %s\n" "${f##*/}"
  done' sh {} +

For the second one:

find "$TARGET_DIR//." ! -name . -prune -type f -exec sh -c '
  for f do
    size=$(($(wc -c < "$f") +0)) || continue
    printf %s "$size ${f##*/} "
    file -b -- "$f"
  done' sh {} +