Regex - Checking if [x]/[y] y is greater than x

Viewed 134

I'm trying to capture [x]/[y] and if y is greater than x using a regex pattern. The input is in the second column ($2)

Example input:

NAME1 0/1
NAME2 0/2
NAME3 1/2
NAME4 1/3
NAME5 2/2
NAME6 1/1

Output:

NAME1 0/1
NAME2 0/2
NAME3 1/2
NAME4 1/3

What would be the right approach using awk?

I've done so far:

cat pods | grep -v Completed | awk -e '$2 ~ "[0-9]/[0-9]"'

I'm not sure how to proceed or to check if the second [0-9] is greater.

3 Answers

With your shown samples, please try following awk code. Simple explanation would be, in main program splitting 2nd field using awk's split function and splitting 2nd field into array named arr using field separator /, then checking condition if 2nd element of array is GREATER than 1st element then printing that line.

awk  '{split($2,arr,"/")} arr[2]>arr[1]' Input_file

OR As an alternate solution one could also use:

awk -F' |/' '$3>$2' Input_file

A bit shorter gnu awk using / as field separator:

awk -F/ '$2 > gensub(/.* /, "", "1", $1)+0' file

NAME1 0/1
NAME1 0/2
NAME1 1/2
NAME1 1/3

If you want to match the pattern with digits and a forward slash, another option using gnu awk using a pattern with 2 capture groups, matching 1 or more digits using ([0-9]+) on the left and right of /

The values of the capture groups are in array a which you can use to compare group 2 with group 1.

awk 'match($2, "^([0-9]+)/([0-9]+)$", a) {
  if(a[2]>a[1]) print
}' file

Output

NAME1 0/1
NAME2 0/2
NAME3 1/2
NAME4 1/3

Using awk you can match the pattern and then split on the forward slash

awk '$2 ~ "^[0-9]+/[0-9]+$" {
  split($2,a,"/")
  if(a[2]>a[1]) print
}' file
Related