{'REST_SPS': u'4.1.4.339', 'REST_ROM': u'U32 v2.34 (04/08/2020)', 'REST_SMART': u'2.65', 'Server': 'example', 'REST_ILO': u'2.18 Jun 22 2020', 'REST_1G': u'20.14.62', 'REST_DISK': u'HPD5', 'REST_10G_2': u'14.26.1040', 'REST_IB': u'12.24.1000', 'REST_IE': u'0.2.2.0', 'REST_10G_1': u'14.26.1040'}
上面是这里的一行,我想要输出如下
4.1.4.339, U32 v2.34 (04/08/2020), 2.65, example, 2.18 Jun 22 2020, 20.14.62, HPD5,14.26.1040, 12.24.1000, 0.2.2.0, 14.26.1040
答案1
正如 Steeldriver 建议的那样:
line="{'REST_SPS': u'4.1.4.339', 'REST_ROM': u'U32 v2.34 (04/08/2020)', 'REST_SMART': u'2.65', 'Server': 'example', 'REST_ILO': u'2.18 Jun 22 2020', 'REST_1G': u'20.14.62', 'REST_DISK': u'HPD5', 'REST_10G_2': u'14.26.1040', 'REST_IB': u'12.24.1000', 'REST_IE': u'0.2.2.0', 'REST_10G_1': u'14.26.1040'}"
echo "$line" | python3 -c '
import sys
line = sys.stdin.readline()
d = eval(line)
keys = ["REST_SPS", "REST_ROM", "REST_SMART", "Server", "REST_ILO", "REST_1G", "REST_DISK", "REST_10G_2", "REST_IB", "REST_IE", "REST_10G_1"]
print(", ".join([d[k] for k in keys]))
'
4.1.4.339, U32 v2.34 (04/08/2020), 2.65, example, 2.18 Jun 22 2020, 20.14.62, HPD5, 14.26.1040, 12.24.1000, 0.2.2.0, 14.26.1040
我不是一个真正的Python爱好者,所以这可能需要一些改进。
如果您从文件中读取行,您不想为每一行调用一次 python:在 python 中进行处理。
答案2
命令
awk -F "," '{for(i=1;i<=NF;i++){sub(/.*:/,"",$i);print $i}}' filename|sed -r "s/^\s+//g"| sed "s/[u'}]//g"| awk 'ORS="," {print $0}'|sed "s/,$//g"
输出
4.1.4.339,U32 v2.34 (04/08/2020),2.65,example,2.18 Jn 22 2020,20.14.62,HPD5,14.26.1040,12.24.1000,0.2.2.0,14.26.1040
答案3
您可以完全做到这一点,sed
但是,正如您所看到的,sed
这不是这个特定用例的理想工具,除非您喜欢编写很长的sed
命令。我强烈建议您使用awk
它。
$ sed -e 's/[{}]//g; s/, /,/g; s/: /\n/g' file | \
sed -e "s/^u//g; s/'//g; s/,/\n/g" | sed -n 'g;n;p' | \
sed -n 's/.*/&,/;H;$x;$s/,\n/, /g;$s/\n\(.*\)/\1/;$s/\(.*\),/\1/;$p'
4.1.4.339, U32 v2.34 (04/08/2020), 2.65, example, 2.18 Jun 22 2020, 20.14.62, HPD5, 14.26.1040, 12.24.1000, 0.2.2.0, 14.26.1040