Wc コマンド - 行数、単語数、文字数をカウントする
wc (word count の略) は、Unix/Linux オペレーティング システムのコマンド ライン ツールで、改行カウント、ワード カウント、バイト数、バイト数を確認するために使用されます。標準出力へのファイル引数で指定されたファイル内の文字数を取得し、すべての名前付きファイルの合計数を保持します。
File パラメータを定義すると、wc コマンドはファイル名と要求された数を出力します。 File パラメータにファイル名を定義しない場合は、合計数のみが標準出力に出力されます。
この記事では、wc コマンドを使用してファイルの改行、単語、文字、またはバイト数を計算する方法を実際の例とともに説明します。
wc コマンド構文
wc コマンドの構文を以下に示します。
wc [options] filenames
以下は、wc コマンドで提供されるオプションと使用法です。
wc -l
– ファイル内の行数を出力します。wc -w
– ファイル内の単語数を出力します。wc -c
– ファイル内のバイト数を表示します。wc -m
– ファイルの文字数を出力します。wc -L
– ファイル内の最も長い行の長さのみを出力します。
この記事では、利用可能ないくつかの引数と例を使用して「wc」コマンドを使用する方法を見てみましょう。コマンドのテストには「tecmint.txt」ファイルを使用しました。
以下に示すように cat コマンドを使用して、tecmint.txt ファイルの出力を調べてみましょう。
cat tecmint.txt
Red Hat
CentOS
AlmaLinux
Rocky Linux
Fedora
Debian
Scientific Linux
OpenSuse
Ubuntu
Xubuntu
Linux Mint
Deepin Linux
Slackware
Mandriva
1. WC コマンドの基本的な例
パラメーターを渡さずに「wc」コマンドを実行すると、「tecmint.txt」ファイルの基本的な結果が表示されます。以下に示す 3 つの数字は12 (行数)、16です。 > (ワード数)、およびファイルの112 (バイト数)。
wc tecmint.txt
12 16 112 tecmint.txt
2. ファイル内の行数をカウントする
オプション「-l
」を使用してファイル内の改行の数を数えます。これは、指定されたファイルの行数を出力します。たとえば、次のコマンドはファイル内の改行数を表示します。
出力では、最初のフィールドはカウントとして割り当てられ、2 番目のフィールドはファイルの名前です。
wc -l tecmint.txt
12 tecmint.txt
3. ファイル内の単語数を数える
wc コマンドの -w
引数は、ファイル内のワード数を出力します。次のコマンドを入力して、ファイル内の単語をカウントします。
wc -w tecmint.txt
16 tecmint.txt
4. ファイル内の文字数をカウントする
wc コマンドでオプション -m
を使用すると、ファイル内の合計の文字数が出力されます。
wc -m tecmint.txt
112 tecmint.txt
5. ファイル内のバイト数をカウントする
オプション -c
を使用すると、ファイルのバイト数が出力されます。
wc -c tecmint.txt
112 tecmint.txt
6. ファイル内の最長行の長さを表示
'wc' コマンドでは引数 '-L
' を使用でき、最長文字の長さ (文字数) を出力するために使用できます。ファイル内の ) 行。
したがって、ファイル内に最長の文字行 (「Scientific Linux」) が存在します。
wc -L tecmint.txt
16 tecmint.txt
7. wc コマンドオプションを確認する
wc コマンドの詳細とヘルプについては、コマンド ラインから「wc --help
」または「man wc
」を実行してください。
wc --help
OR
man 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. A word is a non-zero-length sequence of
characters delimited by white space.
With no FILE, or when FILE is -, read standard input.
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 maximum display width
-w, --words print the word counts
--help display this help and exit
--version output version information and exit
GNU coreutils online help: <https://www.gnu.org/software/coreutils/>
Full documentation at: <https://www.gnu.org/software/coreutils/wc>
or available locally via: info '(coreutils) wc invocation'
この記事では、wc コマンドについて学習しました。このコマンドは、テキスト ファイル内の行数、単語数、文字数、バイト数を数える簡単なコマンド ライン ユーティリティです。このような Linux コマンドは他にもたくさんあるので、コマンドライン スキルを学習して習得する必要があります。