matgod
matgod

Reputation: 49

TCL - Check if file contains value of variable and return part of line

I would like to ask about "WHY?" and some help with strange problem with file reading.

I have file with values like :

var1=home
var2=dog

In my code I am trying to find name of variable, get line where it is placed, trim it and receive value (e.g. home)

What I am using to get it:

puts [regexp { $var_name*\s*=\s*\s*(\S+)\s*} $line all ip_ftpAI]

I made also small check before:

if {[string match $var_name "var1"]} { puts " value ok:$var_name"

It is always as true

When I am changing $var_name to normal string like "home" it works but solution is just for one possibility.

Can someone give me some advice how to deal with the problem?

Upvotes: 0

Views: 761

Answers (1)

glenn jackman
glenn jackman

Reputation: 246754

The variable is not being expanded because it is within braces. See https://tcl.tk/man/tcl8.6/TclCmd/Tcl.htm rule #6

Do this to construct the regex:

set var_name "var1"
append regex $var_name {\s*=\s*(\S+)}
if {[regexp -- $regex $line all value]} {
    puts "$var_name value is $value"
}

Instead of append, you can use Tcl's equivalent to sprintf:

set regex [format {%s\s*=\s*(\S+)} $var_name]

Upvotes: 2

Related Questions