Reputation: 79
Input:
set game1 base_ball_10_100_a_b_c
set game2 base_ball_20_200_d_e_f
set game3 base_bat_40_400_j_k_l
set game4 base_bat_50_500_m_n_o
set game5 tennis_ball_10_100_a_b_c
set game6 tennis_ball_20 200_d_e_f
set game7 tennis_bat_40_400_j_k_l
set game8 tennis_bat_50_500_m_n_o
Output needs to be uniquified and print out as below.
set game1 bb1_digit1
set game2 bb1_digit2
set game3 bb1_digit3
set game4 bb2_digit4
set game1 bb3_digit1
set game2 bb3_digit2
set game4 bb4_digit3
set game5 bb4_digit4
How can I replace base_ball
-> bb*
?
How can I replace 10_100_a_b_c
-> digit*
?
What are the tcl command to perform this task?
Upvotes: 0
Views: 67
Reputation: 2610
Here's a quick-and-dirty go at this:
#!/usr/bin/tclsh
set input {
set game1 base_ball_10_100_a_b_c
set game2 base_ball_20_200_d_e_f
set game3 base_bat_40_400_j_k_l
set game4 base_bat_50_500_m_n_o
set game5 tennis_ball_10_100_a_b_c
set game6 tennis_ball_20_200_d_e_f
set game7 tennis_bat_40_400_j_k_l
set game8 tennis_bat_50_500_m_n_o
}
set bbs [list]
set digits [list]
foreach { k1 k2 k3 } $input {
if { ![regexp {^([^0-9]+)(.*)$} $k3 - bb digit] } {
error "invalid input $k3"
}
set bb_index [lsearch -exact $bbs $bb]
if { $bb_index < 0 } {
lappend bbs $bb
set bb_index [lsearch -exact $bbs $bb]
}
set digit_index [lsearch -exact $digits $digit]
if { $digit_index < 0 } {
lappend digits $digit
set digit_index [lsearch -exact $digits $digit]
}
puts "$k1 $k2 bb[expr {${bb_index}+1}]_digit[expr {${digit_index}+1}]"
}
... and the terminal output:
set game1 bb1_digit1
set game2 bb1_digit2
set game3 bb2_digit3
set game4 bb2_digit4
set game5 bb3_digit1
set game6 bb3_digit2
set game7 bb4_digit3
set game8 bb4_digit4
The output is a little different from what's in your question, but I assume this is what you had in mind.
If input is to come from a file, you can replace
set input {
set game1 base_ball_10_100_a_b_c
set game2 base_ball_20_200_d_e_f
set game3 base_bat_40_400_j_k_l
set game4 base_bat_50_500_m_n_o
set game5 tennis_ball_10_100_a_b_c
set game6 tennis_ball_20_200_d_e_f
set game7 tennis_bat_40_400_j_k_l
set game8 tennis_bat_50_500_m_n_o
}
with
set fd [open "name_of_file"]
set input [read $fd]
close $fd
Upvotes: 3