Копировать файл в место назначения на основе ini-файла

Вот код, который я придумал, основываясь на советах @pfnuesel и @Stéphane Chazelas:

#!/bin/bash

preview="false"
found="false"

if [ $# -eq 0 ]; then
    echo "Syntax: ren [-p] expression replacement files..."
else
    if [ "$1" == "-p" ] || [ "$1" == "-P" ]; then
        preview="true"
        shift
    fi

    expression=$1
    replacement=$2
    shift 2

    for file; do
        if [ -f "$file" ]; then
            found="true"
            if [ "$preview" == "true" ]; then
                echo mv -i -- "${file}" "${file/$expression/$replacement}"
            else
                mv -i -- "${file}" "${file/$expression/$replacement}"
            fi
        fi
    done

    if [ "$found" != "true" ]; then
        echo >&2 "Couldn't find files with the specified wildcard"
        exit 1
    fi
fi
2
21.03.2017, 17:01
2 ответа

Это может быть достигнуто в командной строке, но сценарий, который будет запускаться из командной строки, будет более простым решением (я думаю).

Основные шаги:

  • Получите список каталогов для перебора:
    find $ {directory} -mindepth 1 -type d

  • Проверьте каждый каталог на наличие config.ini и image.jpg .
    если [-f $ {подкаталог} /config.ini -a -f $ {подкаталог} /image.jpg]; затем ...

  • Проверьте config.ini на наличие всех правильных частей метки времени.
    различные grep ^ Year = $ {subdir} /config.ini или ^ Month и т. Д.
  • Сделайте копию изображения .jpg файл, используя метку времени.
    cp $ {subdir} /image.jpg $ {copydir} / $ {timestamp} .jpg

Я думаю, что проще и, возможно, безопаснее поместить эти последовательности в сценарий, где вам будет легче вставить читаемый вывод, обработка ошибок и т. д.

Вот пример сценария для выполнения этих шагов:

#!/bin/bash

imagepath="/path/to/images"
copydir="/path/to/copies"

# step 1: find all the directories
for dir in $(find ${imagepath} -mindepth 1 -type d); do
    echo "Procesing directory $dir:"
    ci=${dir}/config.ini
    jp=${dir}/image.jpg

    # step 2: check for config.ini and image.jpg
    if [ -f ${ci} -a -f ${jp} ]; then
        # step 3: get the parts of the timestamp
        year=$(grep ^Year= ${ci}   | cut -d= -f2)
        month=$(grep ^Month= ${ci} | cut -d= -f2)
        day=$(grep ^Day= ${ci}     | cut -d= -f2)
        hour=$(grep ^Hour= ${ci}   | cut -d= -f2)
        min=$(grep ^Minute= ${ci}  | cut -d= -f2)
        sec=$(grep ^Second= ${ci}  | cut -d= -f2)
        ms=$(grep ^Milliseconds= ${ci} | cut -d= -f2)

        # if any timestamp part is empty, don't copy the file
        # instead, write a note, and we can check it manually
        if [[ -z ${year} || -z ${month} || -z ${day} || -z ${hour} || -z ${min} || -z ${sec} || -z ${ms} ]]; then
            echo "Date variables not as expected in ${ci}!"
        else
            # step 4: copy file
            # if we got here, all the files are there, and the config.ini
            # had all the timestamp parts.
            tsfile="${year}-${month}-${day}T${hour}:${min}:${sec}:${ms}.jpg"
            target="${copydir}/${tsfile}"
            echo -n "Archiving ${jp} to ${target}: "
            st=$(cp ${jp} ${target} 2>&1)
            # capture the status and alert if there's an error
            if (( $? == 0 )); then
                echo "[ ok ]"
            else
                echo "[ err ]"
            fi
            [ ! -z $st ] && echo $st
        fi
    else
        # other side of step2... some file is missing... 
        # manual check recommended, no action taken
        echo "No config.ini or image.jpeg in ${dir}!"
    fi
    echo "---------------------"
done

Всегда хорошо быть несколько консервативным с такими сценариями, чтобы случайно не удалить файлы. Этот скрипт выполняет только одно действие копирования, так что это довольно консервативно и не должно повредить вашим исходным файлам. Но вы можете захотеть изменить определенные действия или сообщения вывода, чтобы они лучше соответствовали вашим потребностям.

1
27.01.2020, 22:19
top="$(pwd -P)" \
find . -type d -exec sh -c '
   shift "$1"
   for iDir
   do
      cd "$iDir" && \
      if [ -f "image.jpg" ] && [ -s "config.ini" ]; then
         eval "$(sed -e "/^[[]Acquisition]/,/^Milliseconds/!d
                  /^Year=/b; /^Month=/b; /^Day=/b; /^Hour=/b; /^Minute=/b
                  /^Second=/b; /^Milliseconds=/b; d" config.ini)"
         new=$(printf "%04d-%02d-%02dT%02d:%02d:%02d:%03d\n" \
                  "$Year" "$Month" "$Day" "$Hour" "$Minute" "$Second" "$Milliseconds")
         echo cp -p "image.jpg" "$new"
         cp -p "image.jpg" "$new"
      else
        #echo >&2 "$iDir/image.jpg &/or config.ini file(s) missing or empty."
        :
      fi
      cd "$top"
   done
' 2 1 {} +

#meth-2
find . -type f -name config.ini -exec perl -F= -lane '
    push @A, $F[1] if /^\[Acquisition]/ .. /^Milliseconds/ and
                     /^(?:Year|Month|Day|Hour|Minute|Second|Milliseconds)=/;
    next if ! eof;
    my(@a, $fmt) = qw/-  -  T  :  :  :/;
    (my $d = $ARGV) =~ s|/[^/]+$||;
    print( STDERR "No image.jpg in dir: $d"),next if ! -f $d . "/image.jpg";
    $fmt .= "${_}$a[$a++]" for map { "%0${_}s" } qw/4 2 2 2 2 2 3/;
    print for map { "$d/$_" } "image.jpg", sprintf "$fmt.jpg", @A;
    ($a,@A)=(0);
' {} + | xargs -n 2 echo mv
0
27.01.2020, 22:19

Теги

Похожие вопросы