1
votes

I need to use awk command inside a Tcl script. I have a file like the following. Let's call it giri.txt.

1  what
2  Why
3  When
4  who

I wrote the following code, thinking it will print like this:

what did
why did
when did
who did

set a did
exec cat giri.txt | awk {{ print $2 " " $a }}

But it prints like this:

what what
why why
when when
who who

Can anyone explain why it's printing like this? Can any one suggest a way to use a Tcl variable inside awk?

2

2 Answers

1
votes

You can probably solve everything tcl without invoking awk, but if you really want to do it:

set a did
exec awk "{print \$2, a}" a=$a < giri.txt

If you have doubts about how the command will be expanded replace exec by echo and check the result

echo awk "{print \$2, a}" a=$a
0
votes

Do it without awk:

set a "did"
set stream [open "giri.txt"]
while {[gets $stream line] >= 0} {
  puts "$line $a"
}
close $stream

Even better with a reusable procedure:

proc forEachLine {file args} {
  set stream [open $file]
  while {[gets $stream line] >= 0} {
    {*}$args $line
  }
  close $stream
}

set a "did"
forEachLine "giri.txt" apply {{line} {
  global a
  puts "$line $a"
}}