wcコマンド : 行数・単語数・バイト数の出力

Linuxコマンド(テキスト処理)
2023-09-30
ヒーローイメージ

目次
  1. コマンド概要
  2. コマンド書式
  3. コマンド使用例

コマンド概要

  • wcコマンドは指定されたファイルの行数、単語数、バイト数を出力するコマンドです。
    • ファイルの代わりに-を指定した場合は標準入力を読み込んだ計測結果を出力します。

コマンド書式

コマンド書式
wc [オプション] [ファイル名 ... ]
オプション 説明

-c
--bytes

バイト数を表示する。

-l
--lines

行数を表示する。

-L
--max-line-length

最大長の行の文字数を表示する。

-m
--chars

文字数を表示する。

-w
--words

単語数を表示する。

--files0-from=リスト
 

ファイル名の区切りが「\0」(ヌル文字)であるファイル名リストを読み込む。
リストが「-」の場合は標準出力からファイルリストを読み込む。

コマンド使用例

動作確認環境
項目 補足
OS Amazon Linux 2
シェル bash 4.2.46
コマンド wc (GNU coreutils) 8.22
PS1 [\u@\h \W]$ プロンプト表示形式は [ユーザ名@ホスト名 カレントディレクトリ名]ユーザ権限
PS2 > 継続行のプロンプト表示形式

wc : 行数/単語数/バイト数を出力

  • wcコマンドは指定ファイルの行数、単語数、バイト数を出力するコマンドです。

    コマンド例
    // テスト用ファイル作成
    [username@hostname ~]$ ls -l /usr/bin > tempfile1
    
    
    // ファイルの、行数、単語数、バイト数、を出力
    [username@hostname ~]$ wc tempfile1851  7822 49679 tempfile1
    
    

wc -c : バイト数出力

  • -cオプションを使用すると指定ファイルのバイト数が出力されます。

    コマンド例
    // テスト用ファイル作成
    [username@hostname ~]$ ls -l /usr/bin > tempfile1
    
    
    // ファイルのバイト数を出力
    [username@hostname ~]$ wc -c tempfile149679 tempfile1
    
    

wc -l : 行数を表示

  • -lオプションを使用すると指定ファイルの行数を出力します。

    コマンド例
    // テスト用ファイル作成
    [username@hostname ~]$ ls -l /usr/bin > tempfile1
    
    
    // ファイルの行数を表示
    [username@hostname ~]$ wc -l tempfile1851 tempfile1
    
    

wc -L : 最大長行の文字数出力

  • -Lオプションを使用すると指定ファイルの最大長行の文字数を出力します。

    コマンド例
    // テスト用ファイル作成
    [username@hostname ~]$ ls -l /usr/bin > tempfile1
    
    
    // ファイルの最大長の行の文字数出力
    [username@hostname ~]$ wc -L tempfile1113 tempfile1
    
    

wc -m : 文字数出力

  • -mオプションを使用すると指定ファイルの文字数を出力します。

    コマンド例
    // テスト用ファイル作成
    [username@hostname ~]$ ls -l /usr/bin > tempfile1
    
    
    // ファイルの文字数を出力
    [username@hostname ~]$ wc -m tempfile149679 tempfile1
    
    

wc -w : 単語数出力

  • -wオプションを使用すると指定ファイルの単語数を出力します。

    コマンド例
    // テスト用ファイル作成
    [username@hostname ~]$ ls -l /usr/bin > tempfile1
    
    
    // ファイルの単語数を出力
    [username@hostname ~]$ wc -w tempfile17822 tempfile1
    
    

複数ファイル行数出力

  • --files0-from=オプションを駆使すると、以下の例のとおり複数ファイルの行数を一括で出力することができます。

    コマンド例
    // テスト用ファイル作成
    [username@hostname ~]$ ls -l /usr/bin/ > tempfile1
    [username@hostname ~]$ ls -l /usr/sbin/ > tempfile2
    [username@hostname ~]$ ls -l /usr/local/bin/ > tempfile3
    [username@hostname ~]$ ls -l /usr/local/sbin/ > tempfile4
    
    // ファイルリスト出力(ヌル文字区切り)
    [username@hostname ~]$ find -type f -name "tempfile*" -print0
    ./tempfile1./tempfile2./tempfile3./tempfile4
    
    // 複数ファイルの行数を出力
    [username@hostname ~]$ find -type f -name "tempfile*" -print0 | wc --files0-from=- -l851 ./tempfile1
    507 ./tempfile2
    2 ./tempfile3
    1 ./tempfile4
    1361 total
    
    

コメント


Palette Codeなるべく丁寧にプログラミング関連技術を解説するサイト