Home > Software engineering >  Searching for images matching an ID then copying matched image to a new directory on MacOS using ter
Searching for images matching an ID then copying matched image to a new directory on MacOS using ter

Time:01-31

I have the following files and folders:

./images ./new_images ./ids.txt

In ./images I have many images for example 12345.jpg In ./ids.text I have a list of ids one per line like this:

12345 67890 abcde fghijk etc

I am trying to run code in terminal that checks the ID in ids.txt and then if it matches the ID with an image I'm ./images it copies the matched image to ./new_images.

Here is my code:

img_dir=./images
new_img_dir=./new_images

if [ ! -d $new_img_dir ]
then
    mkdir $new_img_dir
    chmod -R 755 $new_img_dir
fi

while IFS= read -r id; do
    find $img_dir -maxdepth 1 -iname "$id.*" -print -exec cp -v {} $new_img_dir \;
    if [ $? -eq 0 ]; then
        echo "ID: $id"
        echo "Match found and copied to $new_img_dir"
    else
        echo "No match found for ID: $id"
    fi
done < "ids.txt"

I get the response:

ID: 12345 Match found and copied to ./new_images

But the image is never copied to ./new_images

Can anyone please help by looking at my code to see what I am doing wrong?

Many thanks.

CodePudding user response:

This should work:

#!/usr/bin/env sh

# Fail on error
set -o errexit

# ================
# CONFIGURATION
# ================
ID_FILE="ids.txt"
IMG_DIR="images"
IMG_NEW_DIR="new_images"

# ================
# LOGGER
# ================
# Fatal log message
fatal() {
  printf '[FATAL] %s\n' "$@" >&2
  exit 1
}

# Warning log message
warn() {
  printf '[WARN ] %s\n' "$@" >&2
}

# Info log message
info() {
  printf '[INFO ] %s\n' "$@"
}

# ================
# MAIN
# ================
{
  # Create directory if not exists
  [ -d "$IMG_NEW_DIR" ] || {
    info "Creating directory '$IMG_NEW_DIR'"
    mkdir "$IMG_NEW_DIR"
  }

  # Read id(s)
  while IFS='' read -r image_id; do
    # Search images
    images=$(
      find "$IMG_DIR" \
        -maxdepth 1 \
        -mindepth 1 \
        -type f \
        -iname "$image_id.*" \
        -print \
        -exec cp "{}" "$IMG_NEW_DIR" \;
    ) || fatal "Unknown 'find' error"

    if [ -z "$images" ]; then
      warn "No match for ID '$image_id'"
    else
      info "Match for ID '$image_id'"
    fi
  done < "$ID_FILE"

  # Change permissions
  info "Changing permissions '$IMG_NEW_DIR'"
  chmod -R 755 "$IMG_NEW_DIR"
}
  • Related