问题
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
- substr function's 3rd argument is length of the string.
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