Friday, July 22, 2022

[SOLVED] Condition on Nth character of string in a Mth column in bash

Issue

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?


Solution

Could you please try following.

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

OR as per Ed site's suggestion:

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

Explanation: Adding a detailed explanation for above code here.

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.


Answered By - RavinderSingh13
Answer Checked By - Timothy Miller (WPSolving Admin)