Awk substring a single character

2019-07-20 05:39发布

问题:

Here is columns.txt

aaa bbb 3
ccc ddd 2
eee fff 1
3   3   g
3   hhh i
jjj 3   kkk
ll  3   mm
nn  oo  3

I can find the line where second column starts with "b":

awk '{if(substr($2,1,1)=="b") {print $0}}' columns.txt

I can find the line where second column starts with "bb":

awk '{if(substr($2,1,2)=="bb") {print $0}}' columns.txt

Why oh why can't I find the line where the second character in the second column is "b"?:

awk '{if(substr($2,2,2)=="b") {print $0}}' columns.txt 

awk -W version == GNU Awk 3.1.8

回答1:

You can use:

awk 'substr($2,2,1) == "b"' columns.txt
aaa bbb 3
  1. substr function's 3rd argument is length of the string.
  2. print is default action in awk.


回答2:

awk '$2 ~ /^.b/' columns.txt will also work.