Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Searching for a value in a file with two delimiters

I have a datafile in the following format

1|col2|col3|105,230,3,44,59,62|col5
2|col2|col3|43,44|col5
3|col2|col3|1,2,3,4,5,6,7,8|col5
4|col2|col3|1,2,37|col5
  • Delimiter is "|"
  • 4th column is a comma separated set of numbers.
  • I need records that have the number "3" individually in their 4th column but numbers such as 43 or 33 shouldn't count.
  • "3" could be at the start of 4th column, in the middle of 4th column or at the end of 4th column

So, desirable records from above given data are

1|col2|col3|105,230,3,44,59,62|col5
3|col2|col3|1,2,3,4,5,6,7,8|col5

I'm currently using the following command but I'm looking for a more efficient/organized one

awk -F"|" '$4 ~ /,3,/ || $4 ~ /^3,/ || $4 ~ /,3$/'
like image 933
Nitesh Avatar asked Mar 06 '23 20:03

Nitesh


1 Answers

Short GNU awk solution:

awk -F'|' '$4 ~ /\<3\>/' file
  • \< and \> - stand for the start and end of the word respectively

The output:

1|col2|col3|105,230,3,44,59,62|col5
3|col2|col3|1,2,3,4,5,6,7,8|col5

Or a more unified/portable one:

awk -F'|' '$4 ~ /(^|,)3(,|$)/' file
like image 118
RomanPerekhrest Avatar answered Mar 09 '23 10:03

RomanPerekhrest