TCL脚本

时间:2017-10-09 17:41:59

标签: sed tcl

帮我理解sed的语法。我删除了单引号,但代码仍无法正常工作。

set id [open file.txt]
# send the request, get a lot of data
set tok [::http::geturl "http://example.com"-channel $id] 
# cut out the necessary data between two words
exec sed s/{"data1":\(.*\)/data2\1/ $id 
close $id
set ir [open file.txt]
set phone [read $ir]
close $ir
puts $phone

问题是我从以下类型的查询中获取数据

 {"id":3876,"form":"index","time":21,"data":"2529423","service":"Atere","response":"WAIT"} 

大括号是语言语法的一个元素,我需要精确切割单词和大括号之间的值。如何在脚本中实现它。

1 个答案:

答案 0 :(得分:1)

您的代码相当混乱,因为(a)您正在将文件句柄传递给sed命令。那不行。 (b)您将输入通道传递给http而不是输出通道(尝试打开文件进行写入)。

关于潜在问题。 如果您正在接收基本的JSON数据,如图所示。

a)您可以使用JSON解析器:tcllib's json module

b)将其转换为Tcl可以解析为字典的表单

# Assuming the JSON data is in the $data variable, and there's no
# other data present.  This also assumes the data is very basic 
# there are no embedded commas.  Many assumptions means this
# code is likely to break in the future.  A JSON parser would
# be a better choice.
set data "\{"
append data {"id":3876,"form":"index","time":21,"data":"2529423","service":"Atere","response":"WAIT"}
append data "\}"
regsub -all {[{}:",]} $data { } data
set mydatadict $data 
puts [dict get $mydatadict id]

修改

对于http处理:

set tok [::http::geturl "http://example.com"]
set data [::http::data $tok]
::http::cleanup $tok