Print lines starting with an even number

I have the following input,

10
12    a
12 a
14a

      

Next command

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

      

(or the equivalent grep command) returns

12    a   
12 a

      

not 10 because there is an EOL after 10. On the other hand, if I drop the \ s, it also returns 14a, which is not a number.

Thank!

+3


source to share


2 answers


Given the data, here are the commands that will give the 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 a space after 12, and line 16 has a tab after 16.

Run example

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

      

Example 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

      

+1


source


Allow EOL instead of the following characters.



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

      

0


source







All Articles