我有一个示例数据文件:
This is a test.
Unix is Best.
No Linux is the Best.
Space in simple understanding is an area or volume.
Outer space .
我需要输出:
Unix is Best.
Outer space .
教程详情 | |
---|---|
难度级别 | 简单的 |
根权限 | 不 |
要求 | awk 和 bash |
美东时间。阅读时间 | 1分钟 |
如何打印仅包含三 (3) 个单词的所有行?
awk 命令非常适合这种模式处理文本文件。awk 设置名为 NF 的变量。它设置为输入记录中的字段总数。因此,如果 NF 等于 3,则打印该行。语法如下:
awk '{ if ( NF == 3 ) print } ' /路径/到/输入
还可以在循环中使用shell 脚本 while 循环和IFS(内部字段分隔符)来模拟 awk 命令输出:
#!/bin/bash # AWK NF if 条件 (awk '{ if ( NF == 3 ) print } ' $_input) 使用 bash 模拟 # 作者:example <www.example.com> # ------- -------------------------------------------------- -------------------------- _input = "/path/to/data.txt" _word = 3 while IFS = read -r line do set -- $line [ $# -eq $_word ] && echo " $line " done < " $_input "
输出示例:
Unix 是最好的。 外太空 。