#!/usr/bin/env bash # author: Frank Steinmetzger # version: 2022-11-23 # Helper functions ------------------------------------------------------------ # oops, something occured and the script must exit with an error message die() { echo "$PROGNAME error: ${@}" > /dev/stderr exit 1 } # move a file after printing an info text move() { echo " Moving '${1##*/}' -> '$2'" mv -f "$1" "$2" } # print help text usage() { cat <<-EOF $PROGNAME: replace files in one dir with files from another, but keeping the extension Synposis: $PROGNAME [-h|-s DIR] -h show this help and exit -s the source directory from which to pick files. Default: ./$SRC_DIR EOF } # Preamble -------------------------------------------------------------------- PROGNAME="$(basename "$0")" # halt script on any uncaught error set -e # the default directory SRC_DIR="temp" # parse arguments while getopts "hs:" OPTION; do case $OPTION in h) usage; exit 0 ;; s) SRC_DIR="$OPTARG" ;; *) die "Unknown option '$OPTION'" ;; esac done # input sanitisation [ -d "$SRC_DIR" ] || die "'$SRC_DIR' is not a directory or does not exist." [ "$(readlink -m "$SRC_DIR")" = "$(readlink -m .)" ] && die 'Source dir equals destination dir.' # generate list of possible destination files declare -A DST_FILES for DST_FILE in *; do [ -f "$DST_FILE" ] || continue DST_FILES["$DST_FILE"]='' done # Main part ------------------------------------------------------------------- # loop over all files in the source dir for SRC_PATH in "$SRC_DIR"/*; do [ "$SRC_PATH" = "$SRC_DIR/*" ] && die 'Source dir is empty.' SRC_FILE="${SRC_PATH##*/}" # selection of destination file echo echo "Select destination for file '$SRC_FILE':" unset DST_FILE select DST_FILE in '[-skip-]' '[-keep as is-]' "${!DST_FILES[@]}"; do [ "$DST_FILE" ] && break done # don't do anything with the file if [ ! "$DST_FILE" ] || [ "$DST_FILE" = "[-skip-]" ]; then echo " Skipping '$SRC_FILE'" continue fi # move the file to destination without renaming if [ "$DST_FILE" = "[-keep as is-]" ]; then if [ -f "$SRC_FILE" ]; then echo -n "The file '$SRC_FILE' already exists. Overwrite? [y/N] " read INPUT if [ "$INPUT" != "y" ] && [ "$INPUT" != "Y" ]; then echo " Skipping '$SRC_FILE'" continue fi fi move "$SRC_PATH" "./$SRC_FILE" else # replace destination with source file SRC_EXT="${SRC_FILE##*.}" DST_BASE="${DST_FILE%.*}" NEW_DST_FILE="${DST_BASE}.${SRC_EXT}" if [ "$DST_FILE" != "$NEW_DST_FILE" ]; then echo " Removing '$DST_FILE'" rm -f "$DST_FILE" fi move "$SRC_PATH" "./$NEW_DST_FILE" # remove the destination file from future selections unset DST_FILES["$DST_FILE"] fi done