网站搜索

Wc 命令 - 计算行数、字数和字符数


wcword count的缩写)是Unix/Linux操作系统中的一个命令行工具,用于统计换行数、字数、字节数和由标准输出的 File 参数指定的文件中的字符计数,并保存所有命名文件的总数。

当您定义 File 参数时,wc 命令将打印文件名以及请求的计数。如果您没有为 File 参数定义文件名,则它仅将总计数打印到标准输出。

在本文中,我们将通过实际示例讨论如何使用 wc 命令来计算文件的换行符、单词、字符或字节数。

wc 命令语法

wc 命令的语法如下所示。

wc [options] filenames

以下是wc命令提供的选项和用法。

  • wc -l – 打印文件中的行数。
  • wc -w – 打印文件中的字数。
  • wc -c – 显示文件中的字节数。
  • wc -m – 打印文件中的字符数。
  • wc -L – 仅打印文件中最长行的长度。

让我们看看如何使用“wc”命令以及本文中的几个可用参数和示例。我们使用“howtoing.txt”文件来测试命令。

让我们使用 cat 命令找出 howtoing.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”命令将显示“howtoing.txt”文件的基本结果。下面显示的三个数字分别是 12行数)、16 文件的 (字数)和 112字节数)。

wc tecmint.txt

12  16 112 tecmint.txt

2. 计算文件中的行数

使用选项“-l”计算文件中的换行数,该选项打印给定文件的行数。比如说,以下命令将显示文件中换行符的计数。

在输出中,第一个字段指定为计数,第二个字段指定为文件名。

wc -l tecmint.txt

12 tecmint.txt

3. 计算文件中的单词数

wc 命令的 -w 参数会打印文件中的字数。键入以下命令来计算文件中的单词数。

wc -w tecmint.txt

16 tecmint.txt

4. 计算文件中的字符数

将选项 -mwc 命令一起使用时,将打印文件中的总字符数

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 命令,您应该学习并掌握命令行技能。