首页 > 解决方案 > Condition on Nth character of string in a Mth column in bash

问题描述

I have a sample

$ cat c.csv
a,1234543,c
b,1231456,d
c,1230654,e

I need to grep only numbers where 4th character of 2nd column but not be 0 or 1

Output must be

a,1234543,c

I know this only

awk -F, 'BEGIN { OFS = FS } $2 ~/^[2-9]/' c.csv

Is it possible to put a condition on 4th character?

标签: shellawksed

解决方案


请您尝试以下操作。

awk 'BEGIN{FS=","} substr($2,4,1)!=0 && substr($2,4,1)!=1' Input_file

或根据 Ed 网站的建议:

awk 'BEGIN{FS=","} substr($2,4,1)!~[01]' Input_file

说明:在此处添加对上述代码的详细说明。

awk '                                        ##Starting awk program from here.
BEGIN{                                       ##Starting BEGIN section from here.
  FS=","                                     ##Setting field separator as comma here.
}                                            ##Closing BLOCK for this program BEGIN section.
substr($2,4,1)!=0 && substr($2,4,1)!=1       ##Checking conditions if 4th character of current line is NOT 0 and 1 then print the current line.
' Input_file                                 ##Mentioning Input_file name here.

推荐阅读