Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search for the first occurrence of a keyword + print the next column in Linux

Tags:

awk

Suppose I have a file like this:

d,e,c,g,v,c,w,r
g,c,d,c,s,c,g,r
d,y,c,w,t,g,c,f

Now I want to print the column (without the comma delimiter) which appears just after the first 'c' in each row.So my output will look like this

g
d
w

I have tried the code:

awk -F"," '{for (i=1;i<=NF;i++) if ($i == "c") {print $(i+1)};}' filename

But in output I'm getting the columns which appears after each 'c'. I only want the column which appears after the first 'c' . How to solve the problem preferably using awk.

Thanks in advance

like image 354
Sayan Roy Avatar asked Oct 28 '25 11:10

Sayan Roy


2 Answers

Use awk keyword next to skip to next line after the first found "c" on each line:

$ awk -F"," '{for (i=1;i<=NF;i++) if ($i == "c") {print $(i+1);next};}' filename
g
d
w
like image 195
MichalH Avatar answered Oct 31 '25 11:10

MichalH


A sed solution:

sed -n 's/[^c]*c,\([^,]\).*/\1/p' filename

RegEx101 running this

like image 22
Léa Gris Avatar answered Oct 31 '25 11:10

Léa Gris