2

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

AWE
  • 4,045
  • 9
  • 33
  • 42
  • because you're telling `substr()` to return 2 characters (the last arg) and then comparing the resulting 2-char string (e.g. `bb`) to the 1-char string `b` to see if they are identical, which of course they never can be. – Ed Morton Sep 16 '14 at 17:06
  • I have been using this function as substr(field,start,end) where end is the Nth character of string. It had worked so far because I always searched from the first character. – AWE Sep 18 '14 at 06:18

2 Answers2

5

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.
anubhava
  • 761,203
  • 64
  • 569
  • 643
3

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

Etan Reisner
  • 77,877
  • 8
  • 106
  • 148