AMD
AMD

Reputation: 3

Using If-Statement to assign Variable in awk

I am trying to create an awk script file that takes an input file and converts the fourth column of information for the first three lines into a single row. For example, if input.txt looks like this:

XX YY val1 1234
XX YY val2 2345
XX YY val3 3456
stuff random garbage junk extrajunk
useless 343059 random3

I want to print the fourth column for rows 1, 2 and 3 into a single row:

1234 2345 3456

I was trying to do this by using if/else-if statements so my file looks like this right now:

#!/usr/bin/awk -f

{
    if ($1 == "XX" && $3 == "val1") 
    {
             var1=$4; 
    }  
    else if ($1 == "XX" && $3 == "val2") 
    {
             var2=$4; 
    }
    else if ($1 == "XX" && $3 == "val3") 
    {
             var3=$4; 
    }
}

END{ print var1,var2,var3

and then I would print the variables on one line. However, when I try to implement this, I get syntax errors pointing to the "=" symbol in the var2=$4 line.

EDIT

Solved, in my real file I had named the variables funky (yet descriptive) names and that was messing it all up. - Oops.

Thanks

Upvotes: 0

Views: 862

Answers (2)

Ed Morton
Ed Morton

Reputation: 203502

Try this instead:

#!/bin/env bash
awk '
$1 == "XX" { var[$3] = $4 }
END { print var["val1"], var["val2"], var["val3"] }
' "$@"

There's almost certainly a much simpler solution depending on your real requirements though, e.g. maybe:

awk '
{ vars = (NR>1 ? vars OFS : "") $4 }
NR == 3 { print vars; exit }
' "$@"

. For ease of future enhancements if nothing else, don't call awk from a shebang, just call it explicitly.

Upvotes: 1

karakfa
karakfa

Reputation: 67497

you can write something like this

$ awk '$1=="XX"{if($3=="val1") var1=$4
                else if($3=="val2") var2=$4
                else if($3=="val3") var3=$4}
        // .. do something with the vars ....

however, if you just want to print the fourth column of the first 3 lines

$ awk '{printf "%s ", $4} NR==3{exit}' ile
1234 2345 3456

Upvotes: 1

Related Questions