【问题标题】:tcl how to read files and show the certain wordstcl 如何读取文件并显示某些单词
【发布时间】:2021-11-08 07:20:40
【问题描述】:

我前几天有个问题,但是我觉得我的表达不太清楚,我把我的问题分成了很多小问题。

我有很多进程文件,它包含版本,我有它们的正则表达式并将它们导入到一个txt文件中,txt格式就像

 #process #AA_version       #BB_version
   a11      Aa/10.10-d87_1    Bb/10.57-d21_1
   a15      Aa/10.15-d37_1    Bb/10.57-d28_1
   a23      Aa/10.20-d51_1    Bb/10.57-d29_3

每个进程对应其AA_version和BB_version

我想写一个名为 get_tool_version.tcl 的 tcl 来显示 /modify(not replace) 内容

如果我 tclsh get_tool_version.tcl 并输入进程,它将读取 txt 文件并显示它

AA_version=Aa/

BB_version=Bb/

然后我可以修改AA和BB版本的字符串

这是我的代码

set fp [open tool_version r+]
set file_data [read $fp]
close $fp
set data [split $file_data "\n"]
#input the process
set name [gets stdin] ->#and it'll show correspond AAand BB version

但我不知道如何显示它的 AA_version 和 BB_version 以及如何修改它们。

或者我需要使用数组? 谢谢

【问题讨论】:

  • 我的最终目的是修改tool_version正则表达式内容的文件(1.添加新版本2.把已经修改的版本)add#开头。但是我觉得太远了,等这个问题解决了我再提出来

标签: tcl


【解决方案1】:

这是一种方法:

set fh [open tool_version r]
set data [dict create]
while {[gets $fh line] != -1} {
    regexp {(\w+)\s+Aa/(\S+)\s+Bb/(\S+)} $line -> process aa bb
    dict set data $process Aa $aa
    dict set data $process Bb $bb
}
close $fh

set name a15  ;# you would get input from user here
puts "process = $name; Aa = [dict get $data $name Aa]; Bb = [dict get $data $name Bb]"
process = a15; Aa = 10.15-d37_1; Bb = 10.57-d28_1

Tcl 正则表达式语法在这里:https://www.tcl-lang.org/man/tcl8.6/TclCmd/re_syntax.htm

【讨论】:

  • 嗨,但没有 $process 变量
  • 它是在regexp 命令中创建的。您的真实数据看起来与问题中的示例数据有很大不同吗?
  • 嗨,dict set **data** $processs Aa $aa 使用 $data 吗?因为我设置了进程 [gets stdin] 而不是显示没有 aa 变量
  • 或者regexp行需要放-> process aa bb?
  • 我鼓励您参考the documentationdict set 将变量 name 作为第一个参数。
【解决方案2】:

这是我的最终版本

set fp [open tool_version r]
set process [gets stdin]

while {[gets $fh line] != -1} {
  if (regexp $process $line) {
  dict set process1 Aa: [lindex $line 1]
  dict set process1 Bb: [lindex $line 2]
puts "Aa: [lindex $line 1]"
puts "Bb: [lindex $line 2]"
  }
}
close $fp

谢谢~

【讨论】:

  • 在答案中解释一下您更改或做了什么可能会很好。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-27
  • 2021-02-09
  • 2015-06-26
  • 2016-01-19
  • 2015-01-12
  • 2012-04-28
相关资源
最近更新 更多