날짜 또는 파일 이름을 기준으로 파일을 이동하는 스크립트 만들기

날짜 또는 파일 이름을 기준으로 파일을 이동하는 스크립트 만들기

파일을 디렉토리에 계속 저장하는 FTP 프로세스가 있습니다. 생성 날짜는 다음 형식으로 파일 이름의 일부입니다.

YYYY-MM-DD-HH-MM-SS-xxxxxxxxxxx.wav

생성 날짜를 기준으로 파일을 다른 디렉터리로 이동하고 싶습니다. 파일 이름이나 날짜 스탬프 중 더 쉬운 것을 사용할 수 있습니다. 월과 연도만 고려하면 됩니다. 다음 형식을 사용하여 디렉터리를 만들었습니다.

Jan_2016
Feb_2016

수동으로 디렉토리를 생성하고 파일을 이동했지만, 디렉토리가 존재하지 않는 경우 디렉토리를 생성하는 bash 스크립트를 사용하여 이를 자동화하고 싶습니다.

지금까지 내가 한 일은 디렉토리를 수동으로 생성한 후 다음 명령을 실행하는 것이었습니다.

MV ./2016-02*.wav Feb_2016/

답변1

### capitalization is important. Space separated.
### Null is a month 0 space filler and has to be there for ease of use later.
MONTHS=(Null Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec)

cd /your/ftp/dir                  ### pretty obvious I think
for file in *.wav                 ### we are going to loop for .wav files
do                                ### start of your loop
    ### your file format is YYYY-MM-DD-HH-MM-SS-xxxxxxxxxx.wav so
    ### get the year and month out of filename
    year=$(echo ${file} | cut -d"-" -f1)
    month=$(echo ${file} | cut -d"-" -f2)
    ### create the variable for store directory name
    STOREDIR=${year}_${MONTHS[${month}]}

    if [ -d ${STOREDIR} ]         ### if the directory exists
    then
        mv ${file} ${STOREDIR}    ### move the file
    elif                          ### the directory doesn't exist
        mkdir ${STOREDIR}         ### create it
        mv ${file} ${STOREDIR}    ### then move the file
    fi                            ### close if statement
done                              ### close the for loop.

경험이 없는 사람에게는 이것이 좋은 출발점이 될 것입니다. 이러한 지침과 명령을 기반으로 스크립트를 작성해 보세요. 막히면 도움을 요청할 수 있습니다

답변2

이 스크립트가 도움이 될 수 있습니다. (실제 mv 파일의 에코를 제거하십시오):

#!/bin/bash

shopt -s nullglob

month=(Jan Feb Mar May Apr Jun Jul Aug Sep Oct Nov Dec)

for y in 2016; do
    for m in {01..12}; do
        fn="$y-$m"
        dn="${month[10#$m-1]}_$y"
        [[ ! -d $dn ]] && mkdir -p "$dn"
        for file in ./"$fn"*.wav; do
            echo mv "$file" "./$dn/${file#\./}"
        done
    done
done

관련 정보