확장자를 기준으로 파일을 정렬하는 스크립트가 실패합니다.

확장자를 기준으로 파일을 정렬하는 스크립트가 실패합니다.

손상된 디스크에서 파일을 복구하고 있는데 dir1, dir2, ...라는 폴더에 무작위로 정렬되어 있습니다.

확장자를 기준으로 폴더를 정렬하는 스크립트를 만들려고 합니다.

문제는 일부 파일에 확장자가 없고 스크립트가 실제로 해당 파일을 무시해야 할 때 각 파일에 대한 폴더를 생성한다는 것입니다.

이것은 내 코드입니다.

#!/bin/sh

BASEPATH=/media/potato/toshiba/WD320
SOURCEPATH=$BASEPATH/recovered/*
DESTINATIONPATH=$BASEPATH/sorted
DELIMITER="."

function iterateFolder {
    for filename in $1; do
            #checks if file is actually a folder
            #if it is a folder call this function again
            if [ -d $filename ] ;
            then
                    echo "iterating folder $filename"
                    iterateFolder "$filename/*"
            else            
                    #checks if the name of the file has extension ( actually it checks if there is "." in the name of the file)
                    #if it doesn't, ignore the file

                    if [ -z "${filename##*$DELIMITER*}" ] ;
                    then
                            fileExtension="${filename##*.}"
                            #checks if already exists a folder in the destination folder with the name of the extension
                            if [ ! -d "$DESTINATIONPATH/$fileExtension" ] ;
                            then
                                    newDir="$DESTINATIONPATH/$fileExtension"
                                    echo "creating folder $newDir"
                                    mkdir -p $newDir
                            fi
                    fi
            fi
    done
}
iterafteFolder "$SOURCEPATH"

답변1

당신의 실수는 바로 거기에 있습니다 if [ -z "${filename##*$DELIMITER*}" ] ;. 연산자는 ##문자열에서 항목을 제거하기 위해 정확한 일치를 수행해야 합니다. 따라서 파일 이름에 a가 없으면 .수정되지 않아 조건이 성공합니다 ##. if이를 셸에서 테스트할 수 있습니다.

$ foo=bar
$ if [ -z "${foo##*.*}" ]; then echo 'Yes'; fi
Yes
$

보다 전통적인 접근 방식은 [[=~한정자를 사용하여 정규식을 확인하는 것입니다. 예를 들어:

$ if [[ $foo =~ *.* ]]; then echo 'Yes'; else echo 'No'; fi
No
$

여기에서 자세한 내용을 알아볼 수 있습니다 [[.요점은 [[더 강력하고 유연하지만 쉘 내장이 아닌 시스템 바이너리라는 비용이 들기 때문에 새로운 프로세스를 시작할 때 이론적 성능 저하가 발생한다는 것입니다. 처벌은 거의 미미하므로 걱정할 필요가 없습니다.

관련 정보