[A-00050]Shellでファイル数をカウント

シェルスクリプトを使用してファイル数をカウントする方法を記載しておく。

find . -type file | wc -l

対象ディレクトリは下記のとおり。ディレクトリを除いてファイルのみ表示してくれる。

anonymous-MacBook-Pro:test$ find . -type file
./test2.sh
./test3.sh
./date.txt.bak
./test.csv
./func.sh
./sample.csv
./unitseparator.csv
./test4.log
./date.txt
./test4.sh
./utf.csv
./test.sh
./test5.sh
./sjis.csv
./unitseparator.txt
./callFunc.sh

これにカウント関数である[wc]コマンドをパイプで繋げる。

anonymous-MacBook-Pro:test$ find . -type file | wc -l
      16

ちなみにwcコマンドのオプションに[-lc]でファイル全部のバイト数も下記のコマンドで表示してくれる。

anonymous-MacBook-Pro:test$ find . -type file | wc -lc
      16     201

find関数を使用しない別の方法としてlsコマンドを使用する方法もある。

anonymous-MacBook-Pro:test$ ls | wc -l
      16

ただし下記の場合は注意が必要。lsコマンドで結果を表示した際にカレントディレクト、上位ディレクトリも表示されるのでその分カウントが増える。

anonymous-MacBook-Pro:test$ ls -la
total 128
drwxr-xr-x@ 18 anonymous  staff  576 Jun 14 00:03 .
drwx------+ 11 anonymous  staff  352 Jun 10 11:17 ..
-rwxrwxrwx@  1 anonymous  staff  162 May 28 04:31 callFunc.sh
-rw-------@  1 anonymous  staff   81 Jun  7 14:57 date.txt
-rwxr-xr-x   1 anonymous  staff   90 Jun  7 14:43 date.txt.bak
-rwxrwxrwx@  1 anonymous  staff  156 May 28 04:23 func.sh
-rwxrwxrwx@  1 anonymous  staff  144 May 21 03:04 sample.csv
-rw-r--r--@  1 anonymous  staff   78 May 20 01:53 sjis.csv
-rwxrwxrwx@  1 anonymous  staff  141 Jun  1 09:37 test.csv
-rwxrwxrwx@  1 anonymous  staff   96 May 23 03:33 test.sh
-rwxr-xr-x@  1 anonymous  staff  169 May  6 21:25 test2.sh
-rwxr-xr-x@  1 anonymous  staff  372 May  8 07:47 test3.sh
-rw-r--r--@  1 anonymous  staff   56 May 17 01:22 test4.log
-rwxrwxrwx@  1 anonymous  staff  194 May 17 01:02 test4.sh
-rwxrwxrwx@  1 anonymous  staff  173 May 21 03:12 test5.sh
-rw-r--r--@  1 anonymous  staff   40 May 21 02:17 unitseparator.csv
-rw-r--r--@  1 anonymous  staff  154 May 23 03:41 unitseparator.txt
-rw-r--r--@  1 anonymous  staff  144 May 21 03:04 utf.csv
anonymous-MacBook-Pro:test$ ls -la | wc -l
      19

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

*