如何在 bash 中使用命令 sed 显示具有一定数量单词的行



例如,我有这样的文件:

Hel@@lo hi 123
if  a    equals  b
you
two three four
dany uri four 123
1 2 3333333

我需要该命令将仅打印包含 3 个单词的行。
我试图用sed编写命令,但不知何故它无法识别行尾的字符$


sed '/.+[ ]+.+[ ]+[^ ]+$/!d' $1

对原始代码进行小修改:

$ sed '/^[^ ]+[ ]+[^ ]+[ ]+[^ ]+$/!d' file.txt 
Hel@@lo hi 123
two three four
1 2 3333333

上面将制表符视为单词字符,而不是空格。 它还假定不会有前导或尾随空格。

使用 sed ,但允许任何类型的空格并忽略行上的前导和尾随空格:

$ sed -nr '/^[[:space:]]*[^[:space:]]+[[:space:]]+[^[:space:]]+[[:space:]]+[^[:space:]@]+[[:space:]]*$/p' file.txt
Hel@@lo hi 123
two three four
1 2 3333333

如果使用 Mac OSX 或其他 BSD 平台,请将-r替换为-E,如下所示:

sed -nE '/^[[:space:]]*[^[:space:]]+[[:space:]]+[^[:space:]]+[[:space:]]+[^[:space:]@]+[[:space:]]*$/p' file.txt

使用 awk

awk 'NF==3' file.txt

$ cat file.txt
Hel@@lo hi 123
if  a    equals  b
you
two three four
dany uri four 123
1 2 3333333
$ awk 'NF==3' file.txt
Hel@@lo hi 123
two three four
1 2 3333333

相关内容

最新更新