5

I want to print a particular column number fields in a file while in TCL script.

I tried with exec awk '{print $4}' foo where foo is filename, but it is not working as it gives error

can't read "4": no such variable

How can I do above awk in tcl scripting?

Thanks,

ravi
  • 3,304
  • 6
  • 25
  • 27

1 Answers1

14

The problem is that single quotes have no special meaning in Tcl, they're just ordinary characters in a string. Thus the $4 is not hidden from Tcl and it tries to expand the variable.

The Tcl equivalent to shell single quotes are braces. This is what you need:

exec awk {{print $4}} foo

The double braces look funny, but the outer pair are for Tcl and the inner pair are for awk.

Btw, the Tcl translation of that awk program is:

set fid [open foo r]
while {[gets $fid line] != -1} {
    set fields [regexp -all -inline {\S+} $line]
    puts [lindex $fields 3]
}
close $fid
glenn jackman
  • 238,783
  • 38
  • 220
  • 352
  • Perfect answer. `Awk` is perfectly usable from Tcl, as is `sed` — and sometimes that's the easiest way to do things — but you have to remember that Tcl's syntax is not the same as that of a normal Unix shell. Why does Tcl use braces instead of single quotes? Because they're trivially nestable. – Donal Fellows Jun 08 '13 at 11:28
  • % exec [cat log.file | awk {{print $1}}] can't read "1": no such variable while evaluating {exec [cat log.file | awk {{print $1}}]} Doesn't seem to work for me, am I doing something stupid? Or is there a caveat to the answer? – egorulz Jun 10 '16 at 04:44
  • I'm using tcl 8.4.5 in case that is of relevance. – egorulz Jun 10 '16 at 04:52
  • This does work, so I am guessing the square braces are trying to evaluate the variable. % exec head log.file | awk {{print $1}} Jun Jun Jun Jun Jun Jun Jun Jun Jun – egorulz Jun 10 '16 at 05:05