Forum Discussion

Jnon's avatar
Jnon
Icon for Nimbostratus rankNimbostratus
Mar 30, 2018

string variable

Need to create variable from string with multiple delimiters

 

Example: TXT=my Variable Value, with spaces and other characters, TXT2=More Data for Second variable, TXT3=Additional info,

 

convert to:

 

myVar1 = my Variable Value, with spaces and other characters

 

myVar2 = More Data for Second variable

 

myVar3 = Additional info

 

if I use split with the = and , that works, but I can't use , as a delimiter as some of the strings might have commas, each string will end in a comma, but may have non delimited commas in the string as well. The = sign is always after the string name, and I need to assign the variable based on the string name, but don't want to keep the TXT= as part of the variable. TXT value is either one or two spaces, but for each variable it will always be the same, so myVar1, would always be 3 spaces plus the = as TXT= where myVar2 will always be 4 spaces as TXT1 and the = Would prefer to not use regular expressions, for performance reasons, but may have to if no other solution exists.

 

  • How about this? Split at the string ", TXT" first (there's a space between the command the the T) and grab what's to the right of that string. Using your examples, after the first split, you wind up with:

    TXT=my Variable Value, with spaces and other characters
    2=More Data for Second variable
    3=Additional info,
    

    Then, split each substring at "=" and grab everything to the right of that character, giving you:

    my Variable Value, with spaces and other characters
    More Data for Second variable
    Additional info,
    

    On the very last substring, you may need to remove the last comma. I wasn't sure if the last TXTn= parameter would contain a command at the end or not.

  • Hi,

    You can first use string map to replace separators by a dedicated character

    set tmp [string map {", TEXT=" "|" ", TEXT2=" "|" ", TEXT3=" "|" } $var ] 
    

    Then use split with | as separator.