Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I know which delimiter has occurred first using awk in bash?

Tags:

bash

shell

sed

awk

How to know which delimiter has occurred first using single awk line.

Assume I have a file having contents:

AB BC DE
BC DE AB
DE BC AB

And I want to know which of the three DE,AB,BC has occurred first in each line.

I thought that I could use delimiter BC then take its first field and then BC and then take the first field of AB.

This can be done by:

$ awk -F'AB' '{print $1}' <file>   \
  | awk -F'BC' '{print $1}' <file> \
  | awk -F'DE' '{print $1}' <file>

However, is there any other way in which I can dynamically change delimiter inside awk line and get the above thing done using awk only once?

Edit: Corrected the mistakes done earlier.

like image 896
Jenil Mewada Avatar asked Jan 28 '18 13:01

Jenil Mewada


1 Answers

If this isn't what you want:

awk 'match($0,/AB|BC|DE/){print substr($0,RSTART,RLENGTH)}' file

then edit your question to clarify your requirements and provide concise, testable sample input and expected output.

like image 153
Ed Morton Avatar answered Nov 14 '22 23:11

Ed Morton