Forum Discussion

jsgibbs1's avatar
jsgibbs1
Icon for Nimbostratus rankNimbostratus
Jul 20, 2015

foreach command

I need to parse a data file for a custom string and assign the results to a variable. Each string has a similar prefix and is comma-separated.

 

Example: custom_string_foo=[get this data w/out the brackets], custom_string_bar=[get this data too],custom_string_again=[keep getting data until no more instances of custom_string]

 

From what I have read, it seems the foreach command is the best way to handle this, but I can't figure out how to code it. I would appreciate any assistance.

 

Thx

 

  • Something like this:

    set example {custom_string_foo=[get this data w/out the brackets], custom_string_bar=[get this data too],custom_string_again=[keep getting data until no more instances of custom_string]}
    
    foreach x [split $example ","] {
        log local0. [findstr $x "\[" 1 "\]"]
    }
    

    The split command breaks the larger string into list items, and then the foreach loops through that list and extracts the string between the brackets using the findstr command.

  • The string values don't matter at all. All you care about is that the strings are separated by commas, and that the data you want inside each string is inside square brackets.

    set str {test1=[foo],test2=[bar],test3=[blah]}
    
    foreach x [split $str ","] {
        log local0. [findstr $x "\[" 1 "\]"]
    }
    

    returns:

    foo
    bar
    blah
    
  • You can use two options. The first option is to create a simple list object:

    set str {test1=[foo],test2=[bar],test3=[blah]}
    
    set mylist [list]
    
    foreach x [split $str ","] {
        lappend mylist [lindex [split $x "="] 0]
        lappend mylist [findstr $x "\[" 1 "\]"]
    }
    
    log local0. "mylist = $mylist"
    foreach y $mylist { log local0. $y }
    

    The output of this would be:

    mylist = test1 foo test2 bar test3 blah
    test1
    foo
    test2
    bar
    test3
    blah
    

    Where the odd index is the key and the next even index is the value. Or you can use an array:

    set str {test1=[foo],test2=[bar],test3=[blah]}
    
    foreach x [split $str ","] {
        set thisarray([lindex [split $x "="] 0]) [findstr $x "\[" 1 "\]"]
    
    }
    
    foreach {index value} [array get thisarray] {
        log local0. "$index = $value"
    }
    

    It's output would be:

    test1 = foo
    test2 = bar
    test3 = blah
    

    And then you could access these associative array indices individually.

    log local0. $thisarray(test2)