linuxgreppipetcl

How can i pipe grep outputs to tcl stdin?


There are multiple answers on the same for python and perl but I am unable to find any example for tcl. Basically the intention is to read the output of grep into tcl procedure via pipe. I tried

grep -ri --color -n WRN warnings.log | lint.tcl

content of lint.tcl:

#! /usr/bin/tclsh
lappend a [gets stdin]
puts "[join $a \n]"

But this outputs only first line of the grep match. Is there a while condition around [gets stdin] which can help?


Solution

  • Yes, I suggest you to use a while loop.

    Actually, the issue is that [gets stdin] reads only a single line, so your script stops after reading the first line of output from grep.

    To read all lines from stdin, you should wrap [gets stdin] in a while loop that continues until end-of-file. I would modify lint.tcl script in this way:

    #!/usr/bin/tclsh
    
    set a {}
    
    while {[gets stdin line] >= 0} {
        lappend a $line
    }
    
    puts "[join $a \n]"
    

    And so you run:

    grep -ri --color -n WRN warnings.log | ./lint.tcl
    

    This should now output all matching lines from grep, not just the first one.