Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using awk in tcl script

Tags:

regex

awk

tcl

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,

like image 618
ravi Avatar asked Jun 07 '13 17:06

ravi


People also ask

Can we use awk in TCL script?

Tcl is a good candidate for any tasks that might be programmed in Awk, but is a more general language, and in terms of sheer speed, is outperformed by Awk at many text processing and data extraction tasks.

What is awk in script?

Awk is a scripting language used for manipulating data and generating reports. The awk command programming language requires no compiling and allows the user to use variables, numeric functions, string functions, and logical operators.

Can I use cut with awk?

The awk implementation of cut uses the getopt() library function (see Processing Command-Line Options) and the join() library function (see Merging an Array into a String). The current POSIX version of cut has options to cut fields based on both bytes and characters.

What does awk NF do?

The “NF” AWK variable is used to print the number of fields in all the lines of any provided file. This built-in variable iterates through all the lines of the file one by one and prints the number of fields separately for each line.


1 Answers

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
like image 177
glenn jackman Avatar answered Sep 23 '22 03:09

glenn jackman