toxic_boi_8041
toxic_boi_8041

Reputation: 1482

TCL : How to use variable inside grep in exec

How can i use variable inside grep in exec in TCL

"^STRING__${abc}__STRING__${abc}\[\[:space:\]\]*="

Tried Ways,

exec grep "^STRING__${abc}__STRING__${abc}\[\[:space:\]\]*="
exec grep {^STRING__${abc}__STRING__${abc}\[\[:space:\]\]*=}
exec grep {{^STRING__${abc}__STRING__${abc}\[\[:space:\]\]*=}}

Tried this above solutions, but not able to execute properly.

Thanks

Upvotes: 0

Views: 1463

Answers (1)

Peter Lewerin
Peter Lewerin

Reputation: 13252

I take it that your grep requires the brackets to be escaped? The first Way above will strip away the backslashes, and the second and third won't substitute the variable.

The easiest way to do this is probably to use format:

set regex [format {^STRING__%1$s__STRING__%1$s\[\[:space:\]\]*=} $abc]
exec grep $regex

The principle of it is to write the regex string as you want it to be inside the braces and replace the variable occurrences with %s specifiers, or %1$s to put the same string in more than one place, add the string to be inserted and call format on it.

If you don't need the backslashes after all, it's safe to remove them from the format string (as long as the braces are in place around it).

Documentation: format, set

Upvotes: 3

Related Questions