Home > Enterprise >  tcl expression to rename multiple strings in a file
tcl expression to rename multiple strings in a file

Time:03-08

In a file, I have multiple strings,

valid_packet,
rst_int_reg,
write_enb,
enb_read,
state_lfd, ...

I have to rename the strings in the below format

validpacket
lfd_state
read_enb

I have written an expression to rename a few of the strings

set signals " valid_packet, rst_int_reg, write_enb, read_enb, state_lfd, ..."

set signals [regsub "valid_packet" $signals "validpacket"]
set signals [regsub "enb_read" $signals "read_enb"]
set signals [regsub "state_lfd" $signals "lfd_state"]
puts $signals 

For each string, I had to write the same expression, so is there any optimized way, because if I have to rename many strings in a file, I need to repeat the same expression.

CodePudding user response:

This might be better done with string map which can convert many different words throughout a text in one go, though you'll still have to write out what you're changing from and to as there doesn't seem to be a general pattern (in a regular-expression sense at least).

set signals " valid_packet, rst_int_reg, write_enb, read_enb, state_lfd, ..."

# This is a list of changes to do, but I like to put each transform on its own line
set mapping {
    "valid_packet" "validpacket"
    "enb_read" "read_enb"
    "state_lfd" "lfd_state"
}

# Apply the mapping
set signals [string map $mapping $signals]
puts $signals 
  • Related