Linux 디렉토리에서 재귀 적으로 파일 계산
Linux 디렉토리에서 파일을 재귀 적으로 계산하려면 어떻게해야합니까?
나는 이것을 찾았다:
find DIR_NAME -type f ¦ wc -l
그러나 이것을 실행하면 다음 오류가 반환됩니다.
찾기 : 경로는 표현식 앞에 와야합니다. ¦
이것은 작동합니다.
find DIR_NAME -type f | wc -l
설명:
-type f
파일 만 포함합니다.|
( 및 아님¦
)은find
명령의 표준 출력을wc
명령의 표준 입력으로 리디렉션 합니다.wc
(단어 수의 줄임말) 입력 ( docs ) 에서 줄 바꿈, 단어 및 바이트를 계산 합니다.-l
개행 만 계산합니다.
메모:
- 교체
DIR_NAME
로.
현재 폴더에서 명령을 실행합니다. -type f
카운트에 포함 된 디렉토리 (및 심볼릭 링크)를 제거 할 수도 있습니다 .- 파일 이름에 줄 바꿈 문자가 포함될 수있는 경우이 명령이 초과 계산 될 수 있습니다.
예제가 작동하지 않는 이유에 대한 설명 :
보여준 명령에서 "파이프"( |
)를 사용하여 두 명령을 연결 ¦
하는 것이 아니라 쉘이 명령 또는 이와 유사한 것으로 인식하지 못하는 깨진 막대 ( )를 사용합니다. 이것이 오류 메시지를받는 이유입니다.
현재 디렉토리의 경우 :
find -type f | wc -l
현재 디렉토리 아래의 각 디렉토리에있는 파일 수를 분석하려면 다음을 수행하십시오.
for i in */ .*/ ; do
echo -n $i": " ;
(find "$i" -type f | wc -l) ;
done
물론 한 줄로 모두 처리 할 수 있습니다. 괄호 wc -l
는 누구의 출력 을 시청해야 하는지를 명확히합니다 ( find $i -type f
이 경우).
당신이 사용할 수있는
$ tree
트리 패키지를 설치 한 후
$ sudo apt-get install tree
(Debian / Mint / Ubuntu Linux 시스템에서).
이 명령은 파일 수뿐만 아니라 디렉토리 수도 별도로 표시합니다. -L 옵션은 최대 표시 수준 (기본적으로 디렉터리 트리의 최대 깊이)을 지정하는 데 사용할 수 있습니다.
-a
옵션 을 제공하여 숨겨진 파일도 포함 할 수 있습니다 .
내 컴퓨터 에서 허용되는 답변 rsync
보다 조금 더 빠릅니다 find | wc -l
. 예를 들어 다음 /Users/joe/
과 같이 파일을 계산할 수 있습니다 .
[joe:~] $ rsync --stats --dry-run -ax /Users/joe/ /xxx
Number of files: 173076
Number of files transferred: 150481
Total file size: 8414946241 bytes
Total transferred file size: 8414932602 bytes
두 번째 줄에는 위의 예에서 150,481 개의 파일 수가 있습니다. 보너스로 총 크기 (바이트)도 얻습니다.
비고 :
- 첫 번째 줄은 파일, 디렉터리, 심볼릭 링크 등의 개수이므로 두 번째 줄보다 큰 것입니다.
--dry-run
(또는-n
짧은) 옵션은 실제로 파일을 전송하지하는 것이 중요합니다!/xxx
매개 변수는 빈 또는 비 기존 폴더가 될 수 있습니다./
여기서 사용하지 마십시오 .-x
"파일 시스템 경계를 넘지 않음"옵션을 사용했습니다. 즉,이를 실행하고/
외부 하드 디스크가 연결되어 있으면 루트 파티션에있는 파일 만 계산합니다.
UNIX의 파일 이름은 개행 (예, 개행)을 포함 wc -l
할 수 있으므로 너무 많은 파일을 계산할 수 있습니다. 모든 파일에 대해 점을 인쇄 한 다음 점을 계산합니다.
find DIR_NAME -type f -printf "." | wc -c
여기에 몇 가지 답변을 결합하면 가장 유용한 솔루션은 다음과 같습니다.
find . -maxdepth 1 -type d -print0 |
xargs -0 -I {} sh -c 'echo -e $(find "{}" -printf "\n" | wc -l) "{}"' |
sort -n
공백 괄호와 새 줄을 포함하는 파일 이름과 같은 이상한 것을 처리 할 수 있습니다. 또한 파일 수를 기준으로 출력을 정렬합니다.
-maxdepth
하위 디렉토리도 계산하기 위해 숫자를 늘릴 수 있습니다 . 특히 높은 -maxdepth
숫자 와 결합 된 고도로 중첩 된 디렉토리 구조가있는 경우 이는 잠재적으로 시간이 오래 걸릴 수 있음을 유의하십시오 .
현재 작업 디렉토리에서 얼마나 많은 파일과 하위 디렉토리가 있는지 알고 싶다면이 한 줄짜리를 사용할 수 있습니다.
find . -maxdepth 1 -type d -print0 | xargs -0 -I {} sh -c 'echo -e $(find {} | wc -l) {}' | sort -n
이것은 GNU 방식으로 작동하며 BSD 리눅스 (예 : OSX)의 echo 명령에서 -e를 생략하면됩니다.
오류가 발생하지 않도록하려면 줄 wc -l
바꿈이있는 파일을 보지 마십시오 (2 개 이상의 파일로 계산 됨)
예 : 단일 EOL 문자가있는 단일 파일이있는 경우를 고려하십시오.
> mkdir emptydir && cd emptydir
> touch $'file with EOL(\n) character in it'
> find -type f
./file with EOL(?) character in it
> find -type f | wc -l
2
최소한 gnu wc
는 null로 끝나는 목록 (파일 제외)을 읽고 계산하는 옵션이없는 것처럼 보이기 때문에 가장 쉬운 해결책은 파일 이름을 전달하지 않고 파일이 발견 될 때마다 정적 출력을 보내는 것입니다. 위와 같은 디렉토리에
> find -type f -exec printf '\n' \; | wc -l
1
또는 당신 find
이 그것을 지원한다면
> find -type f -printf '\n' | wc -l
1
명령을 사용할 수 있습니다 ncdu
. Linux 디렉토리에 포함 된 파일 수를 재귀 적으로 계산합니다. 다음은 출력의 예입니다.
진행률 표시 줄이있어 파일이 많은 경우 편리합니다.
Ubuntu에 설치하려면 :
sudo apt-get install -y ncdu
벤치 마크 : https://archive.org/details/cv_corpus_v1.tar(380390 파일, 11GB)를 파일 수를 계산해야하는 폴더로 사용했습니다.
find . -type f | wc -l
: 완료하는 데 약 1 분 20 초ncdu
: 완료하는 데 약 1 분 20 초
tree $DIR_PATH | tail -1
샘플 출력 :
5309 디렉토리, 2122 파일
현재 디렉토리에 몇 개의 파일이 있는지 확인하려면 ls -1 | wc -l
. 이것은 의 출력에서 wc
줄 수를 계산하는 데 사용 됩니다 . dotfile은 계산하지 않습니다. 유의하시기 바랍니다 실제로 당신에게 실제 수보다 파일 수를 하나 개 더 줄 것이 HOWTO의 이전 버전에서 사용 (에 "L"이 아니라 앞의 예에서와 같이 "1"의 그). 이 점에 대해 Kam Nejad에게 감사드립니다.(-l)
ls -1
ls -l
파일 만 계산하고 심볼릭 링크를 포함하지 않으려면 (다른 작업의 예일뿐) 사용할 수 있습니다 ls -l | grep -v ^l | wc -l
(이번에는 "1"이 아닌 "L"이고 여기에 "긴"목록이 필요합니다). . grep
"l"(링크 표시)로 시작하는 행을 확인하고 해당 행 (-v)을 버립니다.
상대 속도 : "ls -1 / usr / bin / | wc -l"은 언로드 된 486SX25에서 약 1.03 초가 걸립니다 (이 시스템의 / usr / bin /에는 355 개의 파일이 있음). " ls -l /usr/bin/ | grep -v ^l | wc -l
"은 약 1.19 초가 걸립니다.
출처 : http://www.tldp.org/HOWTO/Bash-Prompt-HOWTO/x700.html
bash 사용 :
()로 항목 배열을 만들고 #으로 개수를 가져옵니다.
FILES=(./*); echo ${#FILES[@]}
재귀 적으로 파일을 계산하지는 않지만 먼저 간단한 옵션을 보여주고 싶었습니다. 일반적인 사용 사례는 파일의 롤오버 백업을 만드는 것입니다. 그러면 logfile.1, logfile.2, logfile.3 등이 생성됩니다.
CNT=(./logfile*); mv logfile logfile.${#CNT[@]}
bash 4 이상이 globstar
활성화 된 재귀 카운트 (@tripleee에서 언급했듯이)
FILES=(**/*); echo ${#FILES[@]}
재귀 적으로 파일 수를 얻으려면 동일한 방식으로 find를 사용할 수 있습니다.
FILES=(`find . -type f`); echo ${#FILES[@]}
특정 파일 유형을 재귀 적 으로 계산하는 것이 필요한 경우 다음을 수행 할 수 있습니다.
find YOUR_PATH -name '*.html' -type f | wc -l
-l
is just to display the number of lines in the output.
I have written ffcnt to speed up recursive file counting under specific circumstances: rotational disks and filesystems that support extent mapping.
It can be an order of magnitude faster than ls
or find
based approaches, but YMMV.
For directories with spaces in the name ... (based on various answers above) -- recursively print directory name with number of files within:
find . -mindepth 1 -type d -print0 | while IFS= read -r -d '' i ; do echo -n $i": " ; ls -p "$i" | grep -v / | wc -l ; done
Example (formatted for readability):
pwd
/mnt/Vancouver/Programming/scripts/claws/corpus
ls -l
total 8
drwxr-xr-x 2 victoria victoria 4096 Mar 28 15:02 'Catabolism - Autophagy; Phagosomes; Mitophagy'
drwxr-xr-x 3 victoria victoria 4096 Mar 29 16:04 'Catabolism - Lysosomes'
ls 'Catabolism - Autophagy; Phagosomes; Mitophagy'/ | wc -l
138
## 2 dir (one with 28 files; other with 1 file):
ls 'Catabolism - Lysosomes'/ | wc -l
29
The directory structure is better visualized using tree
:
tree -L 3 -F .
.
├── Catabolism - Autophagy; Phagosomes; Mitophagy/
│ ├── 1
│ ├── 10
│ ├── [ ... SNIP! (138 files, total) ... ]
│ ├── 98
│ └── 99
└── Catabolism - Lysosomes/
├── 1
├── 10
├── [ ... SNIP! (28 files, total) ... ]
├── 8
├── 9
└── aaa/
└── bbb
3 directories, 167 files
man find | grep mindep
-mindepth levels
Do not apply any tests or actions at levels less than levels
(a non-negative integer). -mindepth 1 means process all files
except the starting-points.
ls -p | grep -v /
(used below) is from answer 2 at https://unix.stackexchange.com/questions/48492/list-only-regular-files-but-not-directories-in-current-directory
find . -mindepth 1 -type d -print0 | while IFS= read -r -d '' i ; do echo -n $i": " ; ls -p "$i" | grep -v / | wc -l ; done
./Catabolism - Autophagy; Phagosomes; Mitophagy: 138
./Catabolism - Lysosomes: 28
./Catabolism - Lysosomes/aaa: 1
Applcation: I want to find the max number of files among several hundred directories (all depth = 1) [output below again formatted for readability]:
date; pwd
Fri Mar 29 20:08:08 PDT 2019
/home/victoria/Mail/2_RESEARCH - NEWS
time find . -mindepth 1 -type d -print0 | while IFS= read -r -d '' i ; do echo -n $i": " ; ls -p "$i" | grep -v / | wc -l ; done > ../../aaa
0:00.03
[victoria@victoria 2_RESEARCH - NEWS]$ head -n5 ../../aaa
./RNA - Exosomes: 26
./Cellular Signaling - Receptors: 213
./Catabolism - Autophagy; Phagosomes; Mitophagy: 138
./Stress - Physiological, Cellular - General: 261
./Ancient DNA; Ancient Protein: 34
[victoria@victoria 2_RESEARCH - NEWS]$ sed -r 's/(^.*): ([0-9]{1,8}$)/\2: \1/g' ../../aaa | sort -V | (head; echo ''; tail)
0: ./Genomics - Gene Drive
1: ./Causality; Causal Relationships
1: ./Cloning
1: ./GenMAPP 2
1: ./Pathway Interaction Database
1: ./Wasps
2: ./Cellular Signaling - Ras-MAPK Pathway
2: ./Cell Death - Ferroptosis
2: ./Diet - Apples
2: ./Environment - Waste Management
988: ./Genomics - PPM (Personalized & Precision Medicine)
1113: ./Microbes - Pathogens, Parasites
1418: ./Health - Female
1420: ./Immunity, Inflammation - General
1522: ./Science, Research - Miscellaneous
1797: ./Genomics
1910: ./Neuroscience, Neurobiology
2740: ./Genomics - Functional
3943: ./Cancer
4375: ./Health - Disease
sort -V
is a natural sort. ... So, my max number of files in any of those (Claws Mail) directories is 4375 files. If I left-pad (https://stackoverflow.com/a/55409116/1904943) those filenames -- they are all named numerically, starting with 1, in each directory -- and pad to 5 total digits, I should be ok.
Addendum
Find the total number of files, subdirectories in a directory.
$ date; pwd
Tue 14 May 2019 04:08:31 PM PDT
/home/victoria/Mail/2_RESEARCH - NEWS
$ ls | head; echo; ls | tail
Acoustics
Ageing
Ageing - Calorie (Dietary) Restriction
Ageing - Senescence
Agriculture, Aquaculture, Fisheries
Ancient DNA; Ancient Protein
Anthropology, Archaeology
Ants
Archaeology
ARO-Relevant Literature, News
Transcriptome - CAGE
Transcriptome - FISSEQ
Transcriptome - RNA-seq
Translational Science, Medicine
Transposons
USACEHR-Relevant Literature
Vaccines
Vision, Eyes, Sight
Wasps
Women in Science, Medicine
$ find . -type f | wc -l
70214 ## files
$ find . -type d | wc -l
417 ## subdirectories
There are many correct answers here. Here's another!
find . -type f | sort | uniq -w 10 -c
where .
is the folder to look in and 10
is the number of characters by which to group the directory.
find -type f | wc -l
OR (If directory is current directory)
find . -type f | wc -l
형식 필터링을 사용하는이 대체 방법은 사용 가능한 모든 GRUB 커널 모듈을 계산합니다.
ls -l /boot/grub/*.mod | wc -l
시도해 볼 수 있습니다.
find `pwd` -type f -exec ls -l {} ; | wc -l
이것은 완전히 잘 작동합니다. 간단하다. 폴더에있는 파일 수를 계산하려는 경우.
ls | wc -l
ls -l | grep -e -x -e -dr | wc -l
- 긴 목록
- 파일 및 디렉토리 필터링
- 필터링 된 줄을 세어
참고 URL : https://stackoverflow.com/questions/9157138/recursively-counting-files-in-a-linux-directory
'program tip' 카테고리의 다른 글
Oracle JDK와 OpenJDK의 차이점 (0) | 2020.10.02 |
---|---|
R 데이터 프레임에서 NA 값을 0으로 어떻게 대체합니까? (0) | 2020.10.02 |
C에서 부울 값 사용 (0) | 2020.10.02 |
NuGet에서 packages.config의 모든 패키지를 설치 / 업데이트하려면 어떻게하나요? (0) | 2020.10.02 |
Java의 문자열에서 공백 제거 (0) | 2020.10.02 |