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,

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

4 Comments

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.
% 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?
I'm using tcl 8.4.5 in case that is of relevance.
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.