Awk substring a single character

纵饮孤独 提交于 2020-01-04 14:07:11

问题


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.



来源:https://stackoverflow.com/questions/25868784/awk-substring-a-single-character

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!