Udit Gupta
Udit Gupta

Reputation: 3272

Accessing shell variable in awk but not interpreted

I am very new to awk programming ...

Here is my code where I am trying to access shell variable count in awk

ivlen=`cat record.txt | awk -F " " '{printf "%s",$10}'`
echo $ivlen

count=` expr $ivlen / 2 `
echo $count

echo "\nInitialization Vector : (Value) "

  // This one needs attention

Edit :

iv=`awk -v count=$count 'BEGIN {RS=" ";ORS=" ";}     
           {if (NR > 4 && NR < count+4 )print $0}' esp_payload.txt`
echo $iv

Input:

  $cat esp_payload.txt
  0000 5FB4 0000 0041
  0000 0000 0000 0000 0000 0000 0000 0000
  0000 0000 0000 0000 5361 6C74 6564 5F5F
  D678 E0DA A075 5361 02B4 6273 D970 2F72

Output:(required) (I want those 0000 strings 12 in number)

 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000
  // this is what I want not what is displayed

output : (displayed on screen)

 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 5361

Now what is going wrong ?? why one 0000 not printed and why 5361 printed out

Upvotes: 1

Views: 494

Answers (3)

glenn jackman
glenn jackman

Reputation: 247250

Your script is counting 0041\n0000 as a single record because it has no space character in it. You're also getting 0000\n0000 as a single field in your output, but you can't tell because you echo $iv instead of echo "$iv"

Change RS=" " to RS="[ \n]".

Upvotes: 2

Idelic
Idelic

Reputation: 15582

You can pass variables to awk by using -v and your script can be simplified a bit, because {print $0} is the default action:

iv=`awk -v count="$count" 'BEGIN { RS=" "; ORS=" " } 
        (NR > 4 && NR < count)' esp_payload.txt`

Upvotes: 1

Karoly Horvath
Karoly Horvath

Reputation: 96366

Your script is in single quotes, bash doesn't substitue variables in single quoted strings.

The cleanest way to pass parameters to awk: awk 'script.....' count=$count.

Upvotes: 0

Related Questions