如何在 Linux 中获取正好包含 3 个字符的文件行

How to get lines of a file with exactly 3 characters in Linux

我需要一个命令来查找文件中包含 3 个字符的行。我执行 command wc -w field.txt 来列出多少行,但现在我需要确切地知道包含 3 个字符的行。

您可以使用循环并打印长度为 3 的行(在 bash 中):

while IFS= read -r line;
do
   if [[ ${#line} == 3 ]]; then
      echo $line;
   fi
done < file

同样可以使用 awk 来完成:

awk '{if(length([=11=]) == 3) print}' file

Unix/Linux操作系统中的wc(字数统计)命令用于查找由文件参数指定的文件中的换行数、字数、字节数和字符数。

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

wc -l : Prints the number of lines in a file.
wc -w : prints the number of words in a file.
wc -c : Displays the count of bytes in a file.
wc -m : prints the count of characters from a file.
wc -L : prints only the length of the longest line in a file.

当将选项“-c”和“-m”与“wc”命令一起使用时,将分别打印文件中的字节总数和字符总数。例子

[root@domain ~]# wc -c domain.txt

112 domain.txt

[root@domain ~]# wc -m domain.txt

112 domain.txt

不写代码,我给个提示。读取文件的每一行,然后使用 wc -c 命令或 bash 内置命令获取字符数并进行比较以获取该行是否包含三个或任何字符。

grep -c -E "^.{3}$" input.txt

这将计算 (-c) 匹配正则表达式 (-E) "^.{3}$" 的行数,即 "start of line, exactly three of anything, end of line".