Print lines starting with an even number
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 to share