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,
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With