Tcl:替换特定列中的字符串
Tcl: replace string in a specific column
我有下面一行:
^ 1 0.02199 0.03188 0.03667 0.00136 0.04155 0.00000 1.07223 1.07223 -0.47462 0.00335 -0.46457 buf_63733/Z DCKBD1BWP240H11P57PDULVT -
我想用不同的值替换第 3 列,并保持整行的空格不变。
我试过 lreplace - 但空格被删除了。
字符串映射只能替换一个词,但找不到替换确切列的方法。
有人可以指点一下吗?
假设各列至少由 2 个空格分隔,您可以使用如下内容:
set indices [regexp -all -indices -inline {\S+(?:\s\S+)?\s{2,}} $line]
set colCount 1
set newValue 0.01234
foreach pair $indices {
if {$colCount == 3} {
lassign $pair start end
set column [string range $line $start $end]
set value [string trimright $column]
set valueEnd [expr {$end-[string length $column]+[string length $value]}]
set newLine [string replace $line $start $valueEnd $newValue]
} elseif {$colCount > 3} {
break
}
incr colCount
}
如果不需要旧行,可以将 newValue
更改为其他内容或将 newLine
更改为 line
。
另一种方法使用 regsub
将命令注入替换字符串,然后 subst
对其求值。这就像 perl 的 s/pattern/code/e
set newline [subst [regsub {^((?:\s+\S+){2})(\s+\S+)} $line \
{[format "%*s" [string length ""] $newvalue]}]]
我有下面一行:
^ 1 0.02199 0.03188 0.03667 0.00136 0.04155 0.00000 1.07223 1.07223 -0.47462 0.00335 -0.46457 buf_63733/Z DCKBD1BWP240H11P57PDULVT -
我想用不同的值替换第 3 列,并保持整行的空格不变。
我试过 lreplace - 但空格被删除了。 字符串映射只能替换一个词,但找不到替换确切列的方法。
有人可以指点一下吗?
假设各列至少由 2 个空格分隔,您可以使用如下内容:
set indices [regexp -all -indices -inline {\S+(?:\s\S+)?\s{2,}} $line]
set colCount 1
set newValue 0.01234
foreach pair $indices {
if {$colCount == 3} {
lassign $pair start end
set column [string range $line $start $end]
set value [string trimright $column]
set valueEnd [expr {$end-[string length $column]+[string length $value]}]
set newLine [string replace $line $start $valueEnd $newValue]
} elseif {$colCount > 3} {
break
}
incr colCount
}
如果不需要旧行,可以将 newValue
更改为其他内容或将 newLine
更改为 line
。
另一种方法使用 regsub
将命令注入替换字符串,然后 subst
对其求值。这就像 perl 的 s/pattern/code/e
set newline [subst [regsub {^((?:\s+\S+){2})(\s+\S+)} $line \
{[format "%*s" [string length ""] $newvalue]}]]