Artur Fridman
Artur Fridman

Reputation: 31

Print lines starting with an even number

I have the following input,

10
12    a
12 a
14a

The following command

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

(or an equivalent grep command) returns

12    a   
12 a

only and not 10 because there is an EOL following 10. On the other hand, if I drop the \s, 14a is also returned, which is not a number.

Thanks!

Upvotes: 3

Views: 86

Answers (2)

JRG
JRG

Reputation: 4187

With given data, here are commands that would give you expected results.

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: line 10 has nothing after 10, line 12 has space after 12 and line 16 has tab after 16.

Sample Run

[/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

Sample Run(with 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

Upvotes: 1

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799310

Allow an EOL instead of further characters.

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

Upvotes: 0

Related Questions