1

Want to use some custom function (written in tcl) in Unix pipeline ie grep patt file.rpt | tclsh summary.tcl. How to make tcl script to take output from the pipeline, process and out on the commandline as if a normal unix command?

1 Answer 1

2

This is very easy! The script should read input from stdin (probably with gets) and write output to stdout (with puts; this is the default destination).

Here's a very simple by-line filter script:

set lineCount 0
while {[gets stdin line] >= 0} {
    incr lineCount
    puts stdout "$lineCount >> $line <<"
}
puts "Processed $lineCount lines in total"

You probably want to do something more sophisticated!


The gets command has two ways of working. The most useful one here is the one where it takes two arguments (channel name, variable name), writes the line it has read from the channel into the variable, and returns the number of characters read or -1 when it has an EOF (or would block in non-blocking mode, or has certain kinds of problems; you can ignore these cases). That works very well with the style of working described above in the sample script. (You can distinguish the non-success cases with eof stdin and fblocked stdin, but don't need to for this use case.)

Sign up to request clarification or add additional context in comments.

1 Comment

Just to fill in the "other way of working" gets, where no varname is used: while true {set line [gets $fh]; if {[eof $fh]} then break; incr lineCount; puts stdout "$lineCount >> $line <<"} -- you need to explicitly test for eof.

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.