Mervan
Mervan

Reputation: 23

Is there a way to use the Variable without using "echo" within "gawk"?

UNIT="CCC62"

echo $UNIT |
gawk '{match($0,/(.){4}/,a)}{if (a[1] == 7 || a[1] == 6) print $0}'

the above yields expected/wanted results if the variable's 4th character is "6" or "7" then the line is printed, but is there a way of putting the variable in gawk's code and get same results ? and is there a smarter way of doing the following only using gawk that is?

Upvotes: 2

Views: 67

Answers (1)

RavinderSingh13
RavinderSingh13

Reputation: 133680

Could you please try following, fixed your issues in code too.

unit="CCC62"
gawk -v var="$unit" 'BEGIN{split(var,a,"");if (a[4] == 7 || a[4] == 6) print var}'

Explanation: Adding detailed explanation for above.

unit="CCC62"                      ##shell variable
gawk -v var="$unit" '             ##Starting gawk program and sending shell variable unit to awk variable var here -v is ideal way of doing so.
BEGIN{                            ##Since there is NO Input_file so work will be done within BEGIN section only.
                                  ##Which works without mentioning Input_file name too.
  split(var,a,"")                 ##Splitting var into array a with separator of NULL.
  if(a[4] == 7 || a[4] == 6){     ##Checking condition if 4th element of a is either 7 or  6 if yes then do following.
    print var                     ##printing value of var here.
  }
}'

Upvotes: 1

Related Questions