その他

[Linux]wcコマンドの意外な使い方

linuxコマンドにwcコマンドというコマンドがあります。

「wc」は「Word Count」の略で、単語の数をカウントするコマンドです。

下記がオリジナルのwcコマンドのヘルプです。

Usage: wc [OPTION]... [FILE]...
  or:  wc [OPTION]... --files0-from=F
Print newline, word, and byte counts for each FILE, and a total line if
more than one FILE is specified.  With no FILE, or when FILE is -,
read standard input.  A word is a non-zero-length sequence of characters
delimited by white space.
The options below may be used to select which counts are printed, always in
the following order: newline, word, character, byte, maximum line length.
  -c, --bytes            print the byte counts
  -m, --chars            print the character counts
  -l, --lines            print the newline counts
      --files0-from=F    read input from the files specified by
                           NUL-terminated names in file F;
                           If F is - then read names from standard input
  -L, --max-line-length  print the length of the longest line
  -w, --words            print the word counts
      --help     display this help and exit
      --version  output version information and exit

Report wc bugs to bug-coreutils@gnu.org
GNU coreutils home page: <http://www.gnu.org/software/coreutils/>
General help using GNU software: <http://www.gnu.org/gethelp/>
For complete documentation, run: info coreutils 'wc invocation'

日本語で書かれている説明です。

wc [-c] [-l] [-w] [-L] [FILE…]
wcコマンドは、FILE…に指定したファイルのバイト数/単語数/行数を出力します。
オプションを省略した場合は、行数、単語数、バイト数、ファイル名の順に出力します。

オプション
① -c
FILE…に指定したファイルの総バイト数を出力します。改行コードやタブコードなどの制御コードも1バイトとします。
② -l
FILE…に指定したファイルの総行数を出力します。
③ -w
FILE…に指定したファイルの総単語数を出力します。
④ -L
FILE…に指定したファイルの内容で、もっとも長い行のバイト数を出力します。改行コードのバイト数は含みません。

基本の使い方は、ファイルの中身の統計を取るためのコマンドです。

 

ファイル数を調べる

よくファイル数を調査することがありますが、ファイルの数が1桁、2桁のうちはよいですが、3桁以上ともなると正確なファイル数をカウントするのは大変です。

そういったときには、

ls -1 | wc -l

でファイル数を表示させることができます。

lsコマンドのオプションは「-1(数字の1)」です。「-l(アルファベットのl)」にしてしまうと、’ファイル数+1’が表示されるので注意が必要です。

ls -1(数字の1)は、「1ファイルの情報を1行に表示する」というコマンドです。

これは、「リダイレクト」を使って”ls -1″で出力された結果をそのまま、wcコマンドに渡して総行数を出力する(=ファイル数が判る)という動作になります。

 

2016-09-27 H.A

 

タイトルとURLをコピーしました