繁体   English   中英

打印以偶数开头的行

[英]Print lines starting with an even number

我有以下输入,

10
12    a
12 a
14a

以下命令

sed -rn '/^[0-9]*[02468]\s/p'

(或等效的grep命令)返回

12    a   
12 a

只有而不是10,因为有一个EOL跟随10.另一方面,如果我放弃\\ s,也会返回14a,这不是数字。

谢谢!

对于给定的数据,这里有一些命令可以为您提供预期的结果。

search & replacement:

sed -rn '/^[0-9]*[02468] |^[0-9]*[02468]$|^[0-9]*[02468]\t/p' n.txt

sed -rn 's/^[0-9]*[02468] |^[0-9]*[02468]$|^[0-9]*[02468]\t/blah/p' n.txt

search & replacement using awk

awk -F" " '{if ($1 ~ /[02468]$/ && $1 % 2 == 0) print $1}' n.txt

awk -F" " '{if ($1 ~ /[02468]$/ && $1 % 2 == 0) print gensub($1,"blah", 1); else print $0;}' n.txt

NOTE:第10行在10之后没有任何内容,第12行在12之后有空格而第16行在16之后有选项卡。

样品运行

[/c]$ cat n.txt
10
11
12 a
13
14a
16      

[/c]$ sed -rn '/^[0-9]*[02468] |^[0-9]*[02468]$|^[0-9]*[02468]\t/p' n.txt
10
12 a
16

[/c]$ sed -rn 's/^[0-9]*[02468] |^[0-9]*[02468]$|^[0-9]*[02468]\t/blah/p' n.txt
blah
blaha
blah

样品运行(带awk)

[/c]$ cat n.txt
10
11
12 a this is spaced line
13
14a
16      this is tab line

[/c]$ awk -F" " '{if ($1 ~ /[02468]$/ && $1 % 2 == 0) print $0}' n.txt
10
12 a this is spaced line
16      this is tab line

[/c]$ awk -F" " '{if ($1 ~ /[02468]$/ && $1 % 2 == 0) print gensub($1,"blah", 1); else print $0;}' n.txt
blah
11
blah a this is spaced line
13
14a
blah    this is tab line

允许EOL而不是其他字符。

$ sed -rn '/^[0-9]*[02468](\s|$)/p' < data
10
12    a
12 a

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM