Seong-Hyeuk Nam Seong-Hyeuk Nam - 6 months ago 15
Linux Question

Split and compare in awk

I want to split and comparison in awk command.

Input file (tab-delimited)

1 aaa 1|3
2 bbb 3|3
3 ccc 0|2


Filtration


  1. First column value > 1

  2. First value of third column value splitted by "|" > 2



Process


  1. Compare first column value if bigger than 1

  2. Split third column value by "|"

  3. Compare first value of the third column if bigger than 2

  4. Print if the first value bigger than 2 only



Command line (example)

awk -F "\t" '{if($1>1 && ....?) print}' file


Output

2 bbb 3|3


Please let me know command line for above processing.

Answer

You can set the field separator to either tab or pipe and check the 1st and 3rd values:

awk -F'\t|\\|' '$1>1 && $3>2' file

or

awk -F"\t|\\\\|" '$1>1 && $3>2' file

You can read about all this character escaping in this comprehensive answer by Ed Morton in awk: fatal: Invalid regular expression when setting multiple field separators.

Otherwise, you can split the 3rd field and check the value of the first slice:

awk -F"\t" '{split($3,a,"|")} $1>1 && a[1]>=2' file
Comments