substituting variable value in AWK

Hi All,

my requirement is as below.

I need to replace a value in a particular column with a substitution variable(date value) and modified value of the current column value in the same position.

for ex.

i have a record like

02;aaaa;bbbbb;cccccc;dddddd;123456789;hhhhh;12hs;asdf ;

i need to insert date value(whiic is obtained from another record and stored in a variable $dt=20110702) at 6th column(123456) and also modify the current value as 123XXX789.

o/p should be like

02;aaaa;bbbbb;cccccc;dddddd;20110702;123XXX789;hhhhh;12hs;asdf

i need to modify my below code with AWK so that i can substitute the date value (which is stored in a variable $dt) in the 6th column

cat test1 | grep "02" > out
nawk '
  BEGIN {
    FS=OFS=";"
  }
  {$6=substr($6,1,3) "XXX" substr($6,7)}
  1' out >> ofile
  rm out

The file is a huge file and i do not want to open the file and change each line while i need to do some tweeking in the existing code to incorporate this change.Any help is greatly appreciated.

You can set variables in awk with

awk -v VAR="$value" ..

You've got a useless use of cat in there, and a useless temp file. Instead of 'cat file | grep string' you can just do 'grep string file', and instead of 'grep string file > out ; nawk out ...' you can do 'grep string file | awk ...'

Hi Corona,

Can you modify my existing code with a your suggestions.

Thanks!

Don't need the grep at all, awk is for pattern matching! Such as

nawk 'BEGIN { FS=OFS=";" } $1 == "02" {$6=dt OFS substr($6,1,3) "XXX" substr($6,7); print}' dt=$dt test1

Your example from command line:

[mute@sunny ~]$ echo "02;aaaa;bbbbb;cccccc;dddddd;123456789;hhhhh;12hs;asdf ;" | nawk 'BEGIN { FS=OFS=";" } $1 ~ "02" {$6=dt OFS substr($6,1,3) "XXX" substr($6,7); print}' dt=20110702
02;aaaa;bbbbb;cccccc;dddddd;20110702;123XXX789;hhhhh;12hs;asdf ;