TCLguy
TCLguy

Reputation: 11

How to extract elements from a list after a match?

I have a variable and a list as below.

set check a7
set element_list "a1 a2 a3 a4 a5 a6 a7 a8 a9 a10"

I want a list in which I have all elements after a7:

a8 a9 a10

How can I do this? The "element_list" is sorted.

Thanks.

Upvotes: 1

Views: 240

Answers (1)

Schelte Bron
Schelte Bron

Reputation: 4813

You didn't specify what should happen if the "check" element is not in the list. Because you indicated the list is sorted, I assume you will still want the elements that would be after the searched element.

set check a7
set element_list "a1 a2 a3 a4 a5 a6 a7 a8 a9 a10"
set last [lsearch -bisect -dictionary -exact $element_list $check]
puts [lreplace $element_list 0 $last]

The bisect option of lsearch will return the last index where the element is less than or equal to the pattern. Then lreplace can be used to remove everything up to and including that index. This works correctly even if "check" would be before the first element.

Upvotes: 2

Related Questions