Home > database >  Filtering Linux output using AWK
Filtering Linux output using AWK

Time:12-01

I am trying to filter out content from a file but some-why it's not working. My goal is to filter out whatever starts with "build-" and it's age is above 1 day. Sometimes it displays minutes / hours / days, therefore I need to filter 1d, 24h, 1440m and above. ( X >= 1d || X >= 24h || X >= 1440m ).

This is my text file:

NAME              STATUS   AGE
argocd            Active   10d
build-start-a     Active   1d
build-start-b     Active   22h
build-start-s     Active   145m
default           Active   12d
games             Active   9d
kube-node-lease   Active   12d
kube-public       Active   12d
kube-system       Active   12d
start-build-s     Active   96m

This is my command:

cat test.txt | grep "^build-*" | awk '{ if ($3 >= 1d || $3 >= 24h || $3 >= 1440m) print $1 }'

and the result is:

build-start-a
build-start-b
build-start-s

(instead of just "build-start-a", as it is the only one that matches the condition I wish.)

My guess is, bash compares "22h" "145m" and "1d" and assumes "22h" "145m" is greater than "1d" and that is why I see three lines. I tried multiple different if conditions but it didn't work for me. Tried to "hard-code" the values and put "1d" "24h" and it didn't work as well. Tried to implement it using else if but the result was the same.

I'd be grateful to understand what I have done wrong and get your help!

Thanks :)

CodePudding user response:

You may use this awk solution:

awk '
/^build-/ && (
   ($3 ~ /d$/ && $3 0 >= 1) ||
   ($3 ~ /h$/ && $3 0 >= 24) ||
   ($3 ~ /m$/ && $3 0 >= 1440)
)' file

build-start-a     Active   1d

As you can see that we apply a different condition based on the last character in $3. $3 0 converts 3rd column to numeric value.

  • Related