![](/img/trans.png)
[英]How to replace a number with sed command if number%7==0 in bash?
[英]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.