디렉토리의 파일 확장자를 확인하는 Bash 스크립트

디렉토리의 파일 확장자를 확인하는 Bash 스크립트
#!/bin/bash
#Number for .txt files
txtnum=0
#Number of .sh files
shnum=0

for file in "SOME_PATH";do
  #if file has extension .txt
   if [[ $file ==* ".txt"]]
   then 
    #increment the number of .txt files (txtnum)
    txtnum++
   elif [[ $file ==* ".sh"]]
   then 
    #increment the number of .sh files (shnum)
    shnum++
   fi
echo "Number of files with .txt extension:$txtnum"
echo "Number of files with .sh extension:$shnum"

위의 코드는 작동하지 않지만 내가 원하는 논리를 렌더링합니다.

초보자의 경우 bash명령이 정확하지 않을 수도 있습니다.

답변1

편집되었기 때문에 확실하게 말할 수는 없지만 디렉터리의 파일로 확장하려면 SOME_PATH따옴표가 없는 glob이 포함되어 있어야 합니다 . *그것은 다음과 같습니다:

/path/to/*

Next는 [[ $file ==* ".txt"]]유효하지 않습니다. 특히 ==*유효한 비교 연산자가 아닙니다. =~비슷한 방식으로 정규식 비교를 수행 할 수 있지만 [[ $file =~ .*\.txt ]]개인적으로는 확장자를 먼저 추출하여 개별적으로 비교하겠습니다.

다음은 shnum++효과가 없습니다. 쉘 산술 복합 명령 내에서 명령을 실행해야 합니다 ((. 예:((shnum++))

done마지막으로 루프 의 끝 문이 누락되었습니다 for.


다음은 필요한 작업을 수행하는 일부 작동 코드입니다.

#!/bin/bash

txtnum=0
shnum=0

for file in /path/to/files/*; do
    ext="${file##*.}"
    if [[ $ext == txt ]]; then
        ((txtnum++))
    elif [[ $ext == sh ]]; then
        ((shnum++))
    fi
done

printf 'Number of .txt files: %d\n' "$txtnum"
printf 'Number of .sh files: %d\n' "$shnum"

답변2

이 요구 사항을 일반화하여 필요한 만큼 많은 확장을 계산할 수 있습니다. 이를 위해서는 연관 배열을 지원하는 쉘이 필요합니다 bash.

#!/bin/bash
declare -A exts

for path in "${SOME_PATH-.}"/*
do
    # Only files
    [[ -f "$path" ]] || continue

    # Split off the file component, and then its name and extension
    file=${path##*/}
    name=${file%.*} extn=${file##*.}
    # printf "%s -> %s -> %s %s\n" "$path" "$file" "$name" "$extn"

    # Count this extension type
    (( exts[$extn]++ ))
done

# Here is what we want to know
echo "txt=${exts[txt]-0}, sh=${exts[sh]-0}"

답변3

노력하다:

#!/bin/bash
txtnum=0
shnum=0

for file in /some/dir/*;do
  if [[ "${file}" =~ \.txt$ ]];then
    txtnum=$((txtnum+1))
  elif [[ "${file}" =~ \.sh$ ]];then
    shnum=$((shnum+1))
  fi
done

echo "Number of files with .txt extention:${txtnum}"
echo "Number of files with .sh extention:${shnum}"

답변4

필요하지 않으면 반복하지 마십시오. 그렇지 않으면 쉘에서 루프를 반복하지 마십시오.작동하다파일에.

파일 이름이 많은 경우 지금까지 제안된 다른 솔루션보다 빠릅니다.

$ ls /usr/lib | awk -F '[/.]+' \
  '{ ext[$NF]++ } END { for(e in ext){ printf ".%-7s\t%4d\n", e, ext[e]} }' | 
grep -Ew 'so|0' # or extensions of your choice
.0                28
.so               10

타이핑도 줄어듭니다!

관련 정보