使用Python中的分隔字符串创建双引号条目列表

时间:2019-01-29 04:29:35

标签: python shell powershell awk

我有一行类似

date |v3| 0.00| 0.00| 0.00| 0| 0| 7324.00| 0.00| 12278 12276|Tue Jan 29 09:36:47

我要迭代此行并形成类似这样的输出

["date" ,"v3" ,"0.00" ,"0.00" ,"0.00" ,"0" ,"0" ,"7324.00" ,"0.00" ,"12278 12276","Tue Jan 29 09:36:47"]

我想使用shell脚本实现此目标,我该如何实现?

4 个答案:

答案 0 :(得分:3)

第一种解决方案: 。能否请您尝试以下操作。

awk -v s1="\",\"" -v s2="\"" '{gsub(/\|/,s1);$0="[" s2 $0 s2 "]"} 1' Input_file

输出如下。

["date ","v3"," 0.00"," 0.00"," 0.00"," 0"," 0"," 7324.00"," 0.00"," 12278 12276","Tue Jan 29 09:36:47"]

第二种解决方法: 或者,要处理不均匀的空间,请尝试以下方法。

awk -v s1="\",\"" -v s2="\"" -v s3="\" ,\"" '{gsub(/ \||\| /,s3);gsub(/\|/,s1);$0="[" s2 $0 s2 "]"} 1' Input_file

OR(上面的一个非衬里形式):

awk -v s1="\",\"" -v s2="\"" -v s3="\" ,\"" '
{
  gsub(/ \||\| /,s3)
  gsub(/\|/,s1)
  $0="[" s2 $0 s2 "]"
}
1
'  Input_file

输出如下。

["date" ,"v3" ,"0.00" ,"0.00" ,"0.00" ,"0" ,"0" ,"7324.00" ,"0.00" ,"12278 12276","Tue Jan 29 09:36:47"]

答案 1 :(得分:1)

您似乎将信息保存在列表结构[..]中,这与Python中的构造非常同义词,该构造不是容易在bash中实现(具有数组)或Awk

您只需执行以下操作

import json
str='date |v3| 0.00| 0.00| 0.00| 0| 0| 7324.00| 0.00| 12278 12276|Tue Jan 29 09:36:47'
split_str = str.split("|")
wo_spaces = [ str.strip() for str in split_str ]
print( json.dumps( wo_spaces ) )
["date", "v3", "0.00", "0.00", "0.00", "0", "0", "7324.00", "0.00", "12278 12276", "Tue Jan 29 09:36:47"]

答案 2 :(得分:1)

一种简单的sed方式:

sed 's/\s*|\s*/","/g;s/^/["/;s/$/"]/'

输出:

["date","v3","0.00","0.00","0.00","0","0","7324.00","0.00","12278 12276","Tue Jan 29 09:36:47"]

答案 3 :(得分:0)

使用Perl

$ export a='date |v3| 0.00| 0.00| 0.00| 0| 0| 7324.00| 0.00| 12278 12276|Tue Jan 29 09:36:47'
$ echo $a | perl -F"\s*\|\s*" -lane ' $_="\x22".$_."\x22" for(@F); print "[",join(",",@F),"]" '
["date","v3","0.00","0.00","0.00","0","0","7324.00","0.00","12278 12276","Tue Jan 29 09:36:47"]
$