2

This is a question regarding file reading in tcl. I am opening a buffer stream to write and i have only one file handler referece to it Now while reading this buffer line by line, at some condition I have to put all the content of the buffer, Please suggest how can i achieve this. So i am just pasting an example code to explain my requirement.

catch { open "| grep" r } pipe
while { [gets $pipe line] } {
      if { some_condition } {
          ## display all the content of $pipe as string
      }
}

Thanks Ruchi

Ruchi
  • 693
  • 3
  • 14
  • 27

1 Answers1

4

To read from the pipe until it is closed by the other end, just use read $pipe. That then lets you do this:

set pipe [open "| grep" r]
while { [gets $pipe line] >= 0 } {  # zero is an empty line...
    if { some_condition } {
        puts [read $pipe]
        ### Or, to include the current line:
        # puts $line\n[read $pipe]
    }
}

If you want anything from earlier in the piped output, you must save it in a variable.

Donal Fellows
  • 133,037
  • 18
  • 149
  • 215
  • I also advise not putting a `catch` around the `open |...` like in the question, as the error messages you can get are never valid channel names. – Donal Fellows Sep 14 '12 at 12:49
  • Also it should be noted that GNU `grep` uses full buffering by default so if it's really intended to read its output linewise, it's advised to pass it the `--line-buffered` command line option. Not sure about other `grep` implementations. – kostix Sep 14 '12 at 20:26