如何在bash中使用sed命令显示具有一定字数的行
例如,我有这样的文件:如何在bash中使用sed命令显示具有一定字数的行,bash,unix,sed,Bash,Unix,Sed,例如,我有这样的文件: Hel@@lo hi 123 if a equals b you two three four dany uri four 123 1 2 3333333 我需要命令只打印包含3个单词的行。 我试图在sed中编写命令,但不知何故,它无法识别行尾的字符$ 使用awk: awk 'NF==3' file.txt $ cat file.txt Hel@@lo hi 123 if a equals b you two three four dany u
Hel@@lo hi 123
if a equals b
you
two three four
dany uri four 123
1 2 3333333
我需要命令只打印包含3个单词的行。我试图在
sed
中编写命令,但不知何故,它无法识别行尾的字符$
使用
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
对原始代码进行小修改:
$ 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
是否可以只在sed中编写命令?使用我写的语法。是什么让你认为它不能识别
$
?
sed -nE '/^[[:space:]]*[^[:space:]]+[[:space:]]+[^[:space:]]+[[:space:]]+[^[:space:]@]+[[:space:]]*$/p' file.txt