Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在bash中使用sed命令显示具有一定字数的行_Bash_Unix_Sed - Fatal编程技术网

如何在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