簡體   English   中英

如何在bash中使用sed命令顯示具有一定數量單詞的行

[英]How to show line with certain number of words with command sed in bash

例如,我有這樣的文件:

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

我需要該命令僅打印其中包含3個單詞的行。
我試圖在sed編寫命令,但不知何故它無法識別該行末的char $


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

使用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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM