tcl , Search for element after a designated string

Search for element after a designated string


Tag: tcl

I have a script that reads from a file and sorts out certain lines by a keyword. I need to be able to pick out a certain element from each of these discovered lines. The lines in the file are set up lie;

$(eval $(call CreateUvmTest, keyword, element_needed, morestuff...
$(eval $(call CreateUvmTest, keyword, element_needed, morestuff...
$(eval $(call CreateUvmTest, keyword, element_needed, morestuff...
$(eval $(call CreateUvmTest, keyword, element_needed, morestuff...

I am trying to figure out how I would read the lines with the keyword and then write only the element_needed to a file.


the line would be

$(eval $(call CreateUvmTest, keyword, run_test_file, $(run_test_file.exten)

and I am hoping to write this to another file called listfile containing only run_test_file

It is very important that it takes lines only containing keyword in it cause there could be identical lines like this;

$(eval $(call CreateUvmTest, NOT_keyword, run_test_file, $(run_test_file.exten)


Considering your other question, I guess you have to match the lines only if it contains $(eval $(call CreateTest, KEYWORD, I guess you may expect us to literally match the above and then extract the further element needed.


$(eval $(call CreateUvmTest, NOT_keyword, run_test_file1, $(run_test_file.exten)
$(eval $(call CreateUvmTest, keyword, run_test_file2, $(run_test_file.exten)
$(eval $(call CreateUvmTest, NOT_keyword, run_test_file4, $(run_test_file.exten)
$(eval $(call CreateUvmTest, NOT_keyword, run_test_file9, $(run_test_file.exten)
$(eval $(call CreateUvmTest, keyword, run_test_file10, $(run_test_file.exten)


set fp [open input.txt r]
set data [split [read $fp] \n]
close $fp
set outfile [open listfile.txt w] 
foreach line $data {
    if {[regexp {\$\(eval \$\(call CreateUvmTest, keyword, ([^,]+)} $line match element]} {
        puts $element; # Printing in console
        puts $outfile $element; # This goes to the file
close $outfile

Output :


Regex used :

{\$\(eval \$\(call CreateUvmTest, keyword, ([^,]+)}

Till keyword, it is matched literally, then [^,]+ is matching the element need to be extracted.

Note : This is written by the assumption that the data will be separated with comma in each line.


Having issue with back reference in TCL

I have the following code: set a "" regsub -all {.([0-9]+).([0-9]+).} $a {\2 \1} b I am trying to grep 2nd and 3rd octet of the IP address. Expected output: 20 30 Actual output: 20 04 0 What is my mistake here?...

Grepping second pattern after matching first pattern

Is there any grep/sed option which will allow me to match a pattern after matching another pattern? For example: Input file (foos are variable patterns starting with 0 mixed with random numbers preceded by # in front): 0foo1 0foo2 0foo3 \#89888 0foo4 0foo5 \#98980 0foo6 So once I try to...

Quickest way to evaluate a variable in TCL

I have a variable myref set to: set myref {$expect_out(buffer)} What is the quickest way to get the $expect_out(buffer) into myval? set myval [HOWTOEVAL $myref] ...

Tcl Regexp confusion

I have the following code in a tcl script $a_list - {,,} foreach a $a_list {if {[regexp adam [regsub {.*\.} $a {}]] == 1} {puts $a} } My understanding is that this looks for the string adam in $a_list and it matches when adam is the last string....

getting values in R from tkentry() widgets

I'm trying to create a small interactive window in which user (for now me) can enter specific information regarding power calculations (test name, number of groups, type of data) in order to perform the correct kind of power calculation. I know how to do this directly in R, but I...

tkinter TclError: can't find package treectrl

Just installed tktreectrl as shown in this tutorial: but when i try to run my program i'm getting this error. Traceback (most recent call last): File "E:/Python/Competition/", line 36, in <module> listbox = TkTreectrl.MultiListbox(window) File "E:\Programs\Python\lib\site-packages\TkTreectrl\",line 50, in __init__ Treectrl.__init__(self, master, showroot=showroot, **kw) File "E:\Programs\Python\lib\site-packages\TkTreectrl\", line 489, in __init__...

Get items in specific index list of lists

I have a key-value list such as: set x {{a 1} {b 2} {c 3}} I need to extract all the items in index=1 in all sub-lists to get: {1 2 3} ...

Replace several lines of commands with a single variable in tcl

I know I have been asking a lot of questions but I'm still learning tcl and I haven't found anything that similar to this issue anywhere so far. Is it at all possible to replace a set f commands in tcl with one variable function0 for example? I want to...

Expand passed arguments before printing with puts to virtual server

I am having trouble with an expect script not evaluating arguments. Everything in the puts ${file_id} block (simplified obviously) gets placed onto a virtual machine and is later used to for configuration. The block you see puts the same code into a local directory for me to see if things...

Putting a string on same line tcl

I have a nmap output and I need to put strings on different lines on same line. Nmap Output: Nmap scan report for Host is up (0.014s latency). Not shown: 97 closed ports PORT STATE SERVICE 80/tcp open http 1720/tcp open H.323/Q.931 5060/tcp open sip Device type: VoIP adapter|WAP|PBX|webcam|printer...

Convert expect output from DOS to UNIX style in realtime

I write some expect scripts by connecting to a remote host through serial connection. My problem is that the output of the spawned process (enabled with log_user 1) contains DOS-style endings (each line being terminated with ^M when reading logs in VIM). I normally run dos2unix on all logs at...

Getting uniqe elements of the list in the following pattern

I am trying to get lsort command with following behaviour,Lets say i have a variable & set variable {a a a a b b b b c c c c } desired output is a b c d if variable is set variable { b b d d c c...

Running multiple exec commands and waiting to finish before continuing

I know I ask a lot of questions and I know there is a lot on here about this exactly what I am trying to do but I have not been able to get it to work in my script nor figure out why it does not let me do...

How to find corresponding values in columns using TCL

I'm a regular matlab user who needs to do some processing in TCL. I have no experience with tcl so up to now what I have done is by searching on google. Please pardon novice ways... I have data in column A and B which is imported via file Data_1,...

tcl tdom parsing failed due to special charecters in xml tags

I am trying to remove some special characters which was existed in XML tags, we can use some regsubs or string map function to eliminate XML special chars in tagged text, But It is lengthy/time consuming process because our log file was very huge around ~25 MB. Is there any...

Expect, find files with timestamp

I have folder with files as below: RBS_delete20150518-170641.xml RBS_delete20150517-160545.xml ... I'm using expect program, but can't get regexp working on date stamp: if {[file exists /home/ARNE/ARNE/SCRIPTS/RBS_delete[0-9].xml]} ...

Deleting duplicate lines along with original

I have a file which contains patterns on each line, some of which are repeating. i want only those patterns which do not repeat. So, I want to remove all repeating data along with the original pattern. I cannot use sort since i want the patterns to be in same...

TCL parsing a list of arguments to an external call

Im trying to execute a call to a python script through aldec riviera-pro my call is python $python_app_name $python_app_args However my $python_app_args are passed as a single string and not multiple strings resulting in that the python application only sees it as one argument and its execution fails. I've tried...

Executing a test in TCL

I am pretty new with TCL but I am writing a script that will search a file for testcases and filter out ones with specific key words and run these test using exec. It runs the first test fine but once it completes it begins to run the same test...

How to search a a directory tree in TCL for files that end in .so or .a and build a list of those directories

I'm trying to write a set of TCL scripts that helps setup a user's environment for a set of libraries that are not in their standard LD_LIBRARY_PATH as part of a support solution. Since the system is rather sparse in terms of what I can install, I don't really have...

tablelist label color while mouse hovers

I've configured the background color of some lables of my tablelist by using the columnconfigure $ColumnIndex -labelbgmethod. However, the background color changes while the mouse hovers over the labels. I couldn't find any -activebackground method and I wish the background color will stay the same even when the mouse hovers...

TCL access array by reference/name

Let's say I have a regular variable that contains the name of an existing array. array set myarr { key_1 val_2 key_2 val_2 } set myvar myarr I can found nowhere how I can iterate over myarr from myvar!...

How to catch subst exceptions in TCL

Here is a code example: set my_ref {$undefined_array(some_key)} set my_val [subst $my_ref] which returns: can't read "undefined_array(some_key)": no such variable while executing "subst $my_ref" According to Looks like there is no way to catch this right now ...

Search for element after a designated string

I have a script that reads from a file and sorts out certain lines by a keyword. I need to be able to pick out a certain element from each of these discovered lines. The lines in the file are set up lie; $(eval $(call CreateUvmTest, keyword, element_needed, morestuff... $(eval...

Why isn't exception handling built into the “dict get” command?

When dictionaries were first implemented and added to Tcl, why was the dict get command implemented in a way that allows an error to occur if an attempt is made to retrieve a value for a key that is not present in the dictionary? This requires you to wrap the...

How to combine two arrays for form two column data using TCL

I have another question, how would I combine two arrays to form two columns. I've seen a zip command e.g. set n $ puts $output $n However when I save the file it is all in a single line. Kindly advice....

TCL, get full error message in catch command

#!/usr/bin/tclsh proc test {} { aaa } test When I run this script I get error message: invalid command name "aaa" while executing "aaa" (procedure "test" line 2) invoked from within "test" (file "./a.tcl" line 7) If I run test command in catch I get only first line of error...

How to get repeated number in string? [closed]

i want to get number of times particular number repeated in a string? Consider number is 2 , if 22 available in sting means , we should not consider as repeated number. set a "1232163122631261112312" in that 2 is repeated 5 times (we should not take 22 as 2 times...

Pick out certain lines from files

I am writing a tcl script that reads from a file and displays certain lines from this file. I can read from the file n problem but I cant figure out how to pick out certain lines BEFORE filtering out what I don't need. I am reading the file to...

How do I print more than one value per key in Tcl?

array set array_in_twos { set1 table set2 chair set1 chair } foreach combo [array names array_in_twos] { puts "$combo is $array_in_twos($combo)," } outputs: set1 is chair, set2 is chair, It seems the second 'set 1' replaces the first 'set 1'. how do i print all? set1 is table, set2 is...

Returning Some Variable from a “proc” in Tcl

Suppose that a procedure in Tcl is as follows: proc Section {ID x y} { . . "Some calculations do here" . . } Section 1 20 30 Section 2 25 35 Section 3 30 40 Section 4 35 45 Now, I define this: set IDsection {1 3} Then, I...

Using $variable in Parenthesis in Tcl (proc)

A part of my code in tcl is: proc Frame {columnLine} { . . . } Now I want use $variable in parenthesis. For example: set x 2. set columnLine {$x 5. 10. 15.} However, after running Tcl, I face an error! How I do solve this problem?...

Tcl: Producing a Loop (*)

I want to produce a loop in Tcl that if n=2 creates: set Beam_Gravity_Load [subst {$a $b}] if n=3: set Beam_Gravity_Load [subst {$a $a $b}] if n=4: set Beam_Gravity_Load [subst {$a $a $a $b}] if n=5: set Beam_Gravity_Load [subst {$a $a $a $a $b}] and so on. "n" always is...

Tcl crange vs. string range

Why does the Tcl wiki say to consider string range over crange? I know that crange is TclX and string range is not, but are there any other differences? And if not, then why does crange exist?

Using [clock format] through TKinter changes how proc returns “”

I am using TKinter to access an existing Tcl library from Python. One of the Tcl procs looks up values in a list and returns "" if the value is not found. The Python code sees the return value as unicode and checks to see if it is equal to...

expect fails when running proc inside proc

My script works fine (retrieves sftp prompt) when using one proc. But when I try to use proc inside proc, script gets stuck, and I do not know why. Please do not refactor the code, that is not the point, I need to understand what is the issue here. Working...

TCl-Tk How to catch floating point numbers from a file

i'm finding some troubles working on a file containing some floating numbers. These are some rows from my file: 174259 1.264944 -.194235 4.1509e-5 174260 1.264287 -.191802 3.9e-2 174261 1.266468 -.190813 3.9899e-2 174262 1.267116 -.193e-3 4.2452e-2 What i'm trying to do is to find the row where is my desire number...

Itcl What is the read property?

I want to control read access to an Itcl public variable. I can do this for write access using something such as: package require Itcl itcl::class base_model_lib { public variable filename "" } itcl::configbody base_model_lib::filename { puts "in filename write" dict set d_model filename $filename } The configbody defines what...

Error: clock scan “-100000 minutes” -base 1

I just stumbled upon this legacy code, which uses the deprecated clock FreeScan: clock scan "-100000 minutes" -base 1 which leads to an error. However, clock scan "-99999 minutes" -base 1 seems to work. I would be interested in the reason for this limit, or is this a bug?...

TCL: Make code cleaner from nested if-statements

This is a procedure of one of the items of the status bar on i3 window manager on linux. Is run every second. Basically deals with frequency governors. If temperature reaches a certain number then switch to powersave mode, or if a certain application is running, e.g. steam, or the...

real-time TCL exec output

I have the following scenario: if { [catch { exec echo calling a BIG script } exec_msg] } { puts "NOK" puts "output of the BIG script: $exec_msg" } else { puts "OK" puts "output of the BIG script: $exec_msg" } Are there any solutions to print the $exec_msg in...

How to get selective data from a file in TCL?

I am trying to parse selective data from a file based on certain key words using tcl,for example I have a file like this ... ... .. ... data_start 30 abc1 xyz 90 abc2 xyz 214 abc3 xyz data_end ... ... ... How do I catch only the 30, 90...

Line break support in parser (TCL)

So, I have a parser, written in TCL. There are many commands in the parsing file. Now, I need to add support for line breaks. For ex. my_command \ arg1 \ arg2 \ arg3 I have something like this. while { ! [eof $currentFileDescriptor] } { set line [gets $currentFileDescriptor]...

TCL get array value using variable as key name

I have the following array list that contains IANA Cipher Suites IDs (Key Name) with their corresponding names (Values) array set IANA_Ciphers [list {0000} {"TLS_NULL_WITH_NULL_NULL"} \ {0001} {"TLS_RSA_WITH_NULL_MD5"} \ {0002} {"TLS_RSA_WITH_NULL_SHA"} \ {0003} {"TLS_RSA_EXPORT_WITH_RC4_40_MD5"} \ [...] {C0AF} {"TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8"} ] Now I need to be able to access this array's values...

No Such Variable When Using While Loop in Expect

I'm attempting to access a variable within a while loop in expect, but I keep getting an error that the variable doesn't exist. The code in question: #!/usr/bin/expect spawn ./ set timeout 1 ...<extra code>... # Return the time in seconds from epoch proc getTime {year month day hour minute}...

Cannot evaluating variable within IF and For loop using TCL

In following code in TCL I cannot seem evaluate the variable "a" I'm evaluating x and y, in the same For Loop I have a IF statement that is checking for a range between x and y. If valid then I'd like to perform some more calculations within the IF...

Non-Greedy regex acts greedy based on the position of atoms in regex

I came across one situation where I wanted to use non-greedy atom .*? in the regex pattern. set input "Device ID: HOST1 Interface: GigabitEthernet0/1, Port ID (outgoing port): GigabitEthernet2/43 Device ID: HOST2 Entry address(es): Interface: GigabitEthernet0/2, Port ID (outgoing port): GigabitEthernet2/43 " puts "======== Non-Greedy regex starting with some other...

Questions on Regex algorithm (not necessarily EXPECT related)

I'm trying to create a regex to capture the neighbor detail of my devices (example output below). I could hard code each individual line, but I'm looking for a better solution. maybe learn a new algorithm. I'm interested in capturing Device ID (HOST1), Interface (GigabitEthernet0/1), and Port ID (GigabitEthernet2/43). for...

How to match a colon after a close bracket

Why does the following not match the : expect { timeout {puts timedout\n} \[1\]: {puts matched\n} } > expect test.tcl [1]: timedout If I change it and remove the colon the match works: expect { timeout {puts timedout\n} \[1\] {puts matched\n} } $ expect test.tcl [1] matched Or if I...

For loop increment by a non-integer in TCL

I want to implement the following C code in TCL: Float power_pitch = 8 float offset = 7.5 float threshold = 100 for(i=power_pitch+offset ; i<= threshold ; i += power_pitch) I want to implement above forloop in TCL. I have tried the following code in TCL: set power_pitch 8 set...