Method to Scan a Copy Files from a Folder Another Folder with a CSV File

Here is the code to provide the sorting method of getting the files to be copied from a folder to another folder based on the required list of names

#!/bin/bash


CSV_FILE="{CSV_File}.csv"
SOURCE_DIR="{Source_location}P"
DEST_DIR="{destination_location}"


# Create destination directory if not exists
mkdir -p "$DEST_DIR"


# normalize: trim, remove CR, remove all spaces, lowercase
normalize() {
  local s="$1"
  s="${s//$'r'/}"                 # remove CR
  s="${s#"${s%%[![:space:]]*}"}"   # ltrim
  s="${s%"${s##*[![:space:]]}"}"   # rtrim
  s="${s//[[:space:]]/}"           # remove all spaces
  printf '%s' "${s,,}"             # lowercase (bash expansion)
}


declare -A lookup  # lookup[normalized_base]="file1|file2|..."


# Build the lookup (one pass)
shopt -s nullglob
for path in "$SOURCE_DIR"/*; do
  [ -f "$path" ] || continue
  fname="$(basename "$path")"
  base="${fname%.*}"               # remove extension
  key="$(normalize "$base")"
  if [ -z "${lookup[$key]+_}" ]; then
    lookup[$key]="$path"
  else
    lookup[$key]="${lookup[$key]}|$path"
  fi
done
shopt -u nullglob


# Process CSV and copy matches
while IFS=, read -r raw || [ -n "$raw" ]; do
  raw="${raw//$'r'/}"             # remove CR
  raw="${raw#"${raw%%[![:space:]]*}"}"
  raw="${raw%"${raw##*[![:space:]]}"}"
  [ -z "$raw" ] && continue


  # if CSV may contain extension like .webp, strip it
  csv_base="${raw%.*}"
  key="$(normalize "$csv_base")"


  if [ -n "${lookup[$key]+_}" ]; then
    IFS='|' read -r -a files <<< "${lookup[$key]}"
    for f in "${files[@]}"; do
      cp -v -- "$f" "$DEST_DIR/" || echo "Failed to copy: $f"
    done
  else
    echo "Not found: $raw"
  fi
done < "$CSV_FILE"

Leave a comment

Your email address will not be published. Required fields are marked *