디렉터리 이름의 공통 부분이 있는 디렉터리 내의 파일에 액세스하는 가장 좋은 방법

디렉터리 이름의 공통 부분이 있는 디렉터리 내의 파일에 액세스하는 가장 좋은 방법

제목이 완전 자명한데 어떻게 표현해야 할지 모르겠네요. 예를 들어 설명하겠습니다.

다음과 같은 디렉토리 구조가 있습니다.

  • 결과/

       test_0_part1_x000/
       test_0_part2_x010/
       test_0_part3_x122/
       test_1_part1_x121/
       test_1_part2_x009/ 
            ....
    

등. 기본적으로 약 500개의 디렉토리가 포함된 results/ 디렉토리가 있습니다. 이러한 디렉터리는 테스트별로 "그룹화"되어 있으므로 모든 test_0_part* 디렉터리는 동일한 테스트 플랫폼을 참조합니다(약 50개의 테스트가 있다고 가정하면 test_0_*에서 test_49_* 디렉터리가 있습니다).

각 디렉터리에서 파일을 수집하여 디렉터리로 그룹화해야 합니다. 디렉터리가 test_0이면 test_0/이고 test_0_part* 디렉터리의 모든 파일을 포함해야 합니다.

실제로 내 접근 방식은 result/의 모든 디렉터리를 반복하고 디렉터리 이름을 비교하여 파일을 올바른 최종 디렉터리에 수집하는 것입니다. 작동하지만 문제를 처리하기 위해 정규 표현식이나 이와 유사한 것을 사용할 수 있기 때문에 전혀 똑똑해 보이지 않습니다. 불행히도 내 bash 스크립팅과 일반적인 bash에 대한 이해는 여전히 매우 기초적이며 코드를 개선하기 위해 무엇을 살펴봐야 할지 모르겠습니다. 모든 파일을 순차적으로 반복하는 것보다 더 안전한 파일 선택 및 복사를 수행하기 위해 정규식을 활용하고 싶습니다.

내 코드는 다음과 같습니다

    #! /bin/bash
    OUTDIR=""  #output dir - where to place the files from same test
    INFILES=""  #collection of input files for each test

    last_dir="" 
    #iterate through all the directories in result/
    for d in */; do

    subdirname=${d%???????????} #getting only the first part of dir name (i.e. test0, test1, etc)

    #if new directory is different from the last one, then it is related to a new test. move alle the files collected so far to the OUTDIR directory and clean the OUTDIR content
    if [[ "$last_dir" != "$subdirname" &&  ! -z "$last_dir" ]]; then                
            echo "copying for $last_dir test:"
            echo "$INFILES" | tr " " "\n"
            echo "output directory: $OUTDIR"
            mkdir ${OUTDIR}
            mv ${INFILES} ${OUTDIR}/
            OUTDIR=""
    fi
    
    #if output dir is empty, then get the name from the current dir and clean the input files list 
    if [ -z "$OUTDIR" ]; then
            OUTDIR=${subdirname}
            INFILES=""
    fi
    
    # collect file(s) in the current directory and append to the list
    for fname in ${d}*;
    do
            INFILES="${INFILES} ${fname}"
    done

    last_dir=${subdirname}

    done

도움을 주시면 감사하겠습니다!

답변1

, 를 사용하여 zsh모든 파일을 다음 위치로 이동하세요.test_n_part*/*test_n

autoload zmv
mkmv() {mkdir -p -- $2:h && mv -- "$@"}

zmv -n -P mkmv '(test_<->)_part*/(*)' '$1/$2'

( -n원하는 경우 시험 실행을 위해 제거).

(#qD)소스 모드에 추가하면 숨겨진 파일도 이동됩니다.

관련 정보