swap
swap

Reputation: 79

set shell variable in awk and reuse

How can I pass a shell variable to awk, set it, use it in another awk in same line and print it?

I want to save $0 (all fields) into a variable first, parse $6 (ABC 123456M123000) - get '12300', do a range check on it and if it satisfies, print all fields ($0)

part 1: I am trying to do:

line="hello"
java class .... | awk -F, -v '{line=$0}' | awk 'begin my range check code' | if(p>100) print $line }

part2: $6="ABC 123456M123000" ( string that I will parse) Once I store all fields into a variable, I can parse $6 using this:

awk 'begin {FS=" "} { print $2; len=length($2); p=substr($2,8,len)+0 ; print len,p ; if(p>100) print $line }'

But my question is in part1: how to store $0 into a variable so that after my check is done, I can print them?

Upvotes: 1

Views: 954

Answers (2)

glenn jackman
glenn jackman

Reputation: 247002

With the shell:

java ... | while IFS= read -r line ; do
    sixth=$(IFS=,; set -- $line; echo "$6")
    val=${sixth:11}
    (( $val > 100 )) && echo "$line"
done

Some bash-isms there.

Upvotes: 0

William Pursell
William Pursell

Reputation: 212374

It's not clear why you need multiple invocations of awk. From your description, it looks like you are just trying to do:

... | awk -F, '{split( $6, f, "M" )} f[2] > min' min=100

or, if you can't split on 'M' but need to use substr (or some other method to extract the desired value):

... | awk -F, '{ split( $6, f, " " )} 0+substr( f[2], 8 ) > min' min=100

Upvotes: 2

Related Questions