linux - 在 shell 脚本中获取逗号分隔值

标签 linux shell sh

我有一个包含多行的文件,如以下字符串。我需要提取 id 和 obj 的值。

{"Class":"ZONE","id":"DEV100.ZN301","name":"3109 E BTM","zgroup":"EAST FLOOR 3","prog":"","members":[{"obj":"DEV300.WC3"},{"obj":"DEV300.WC4"},{"obj":"DEV300.WC7"},{"obj":"DEV300.WC10"}]}

我正在使用以下命令获取输出:

[user@server ~]$ cat file.txt | grep "\"Class\":\"ZONE\"" | while IFS="," read -r a b c d e f ; do echo "$b$f";done | grep ZN301

输出:

"id":"DEV100.ZN301""members":[{"obj":"DEV300.WC3"},{"obj":"DEV300.WC4"},{"obj":"DEV300.WC7"},{"obj":"DEV300.WC10"}]}

我的目标是获得以下输出:

DEV100.ZN301 : DEV300.WC3 , DEV300.WC4 , DEV300.WC7 , DEV300.WC10

请帮帮我。谢谢!

最佳答案

jq -r 'select(.Class == "ZONE") | (.id + " : " + ([.members[] | .obj] | join(" , ")))'

...或者,依靠 Python 解释器:

parse_json() {
  python -c '
import sys, json
for line in sys.stdin:
  line = line.strip()    # ignore trailing newlines
  if not line: continue  # skip blank lines
  doc = json.loads(line)
  if doc.get("Class") != "ZONE":
    continue
  line_id = doc.get("id")
  objs = [m.get("obj") for m in doc.get("members", [])]
  sys.stdout.write("%s : %s\n" % (line_id, " , ".join(objs)))
'
}

parse_json 

关于linux - 在 shell 脚本中获取逗号分隔值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50614855/

相关文章:

php - 使用 php 邮件发送的邮件未显示

android - 通过 wifi/热点的 ADB 不工作

c - 如何通过网络完全控制终端?

shell - shell 中的运算符 $() 的名称是什么?

shell - cron 作业出错,但在 shell 上工作正常

linux - 使用 bash 添加一个常数来移动文件名

java - linux中在哪里添加JAVA_HOME和MAVEN路径​​变量

linux - 通过 shell 脚本为用户的 sudoers 添加 sudo 权限

shell - 通过 pid 杀死 uWSGI 的自定义 shell 脚本

bash - 不存在文件上的 Shell 脚本源终止脚本