Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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,

share|improve this question

1 Answer 1

up vote 6 down vote accepted

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
share|improve this answer
    
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 8 '13 at 11:28

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.