1

I'm facing a problem while trying to pass a variable value to a grep command.

In essence, I want to grep out the lines which match my pattern and the pattern is stored in a variable. I take in the input from the user, and parse through myfile and see if the pattern exists(no problem here).

If it exists I want to display the lines which have the pattern i.e grep it out.

My code:

if {$a==1} {
      puts "serial number exists"
      exec grep $sn myfile } else {
      puts "serial number does not exist"}

My input: SN02

My result when I run grep in Shell terminal( grep "SN02" myfile):

serial number exists
SN02 xyz rtw 345
SN02 gfs rew 786

My result when I try to execute grep in Tcl script:

serial number exists

The lines which match the pattern are not displayed.

4
  • Check [this] for hints about using exec. Also, put the } else { on its own line. My TCL is a bit rusty, so I'm not sure if either is the real issue ;-) Commented Feb 11, 2019 at 6:57
  • Hi, so the reason i put the else on the same line as the closing braces is it threw an error while executing the script. Apparently you need to include else in the same line where the if has its closing brace. Commented Feb 11, 2019 at 7:03
  • Yes that is right, but I said, put the whole } else {-fragment (braces and else-keyword) on its own line. Commented Feb 11, 2019 at 7:04
  • wow, this worked. Appreciate the help! (i'm new to Tcl, so the small nuances always get me) Commented Feb 11, 2019 at 7:06

1 Answer 1

2

Your (horrible IMO) indentation is not actually the problem. The problem is that exec does not automatically print the output of the exec'ed command*.

You want puts [exec grep $sn myfile]

This is because the exec command is designed to allow the output to be captured in a variable (like set output [exec some command])

* in an interactive tclsh session, as a convenience, the result of commands is printed. Not so in a non-interactive script.

To follow up on the "horrible" comment, your original code has no visual cues about where the "true" block ends and where the "else" block begins. Due to Tcl's word-oriented nature, it pretty well mandates the one true brace style indentation style.

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

Comments

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.