grep 语句中的 if/else

grep 语句中的 if/else

我试图找到 的所有实例"type":"FollowEvent",然后在这些实例中,如果字符串"actor":后面没有跟随,则捕获紧随 后面{的字符串。否则,捕获紧随 后面的包含在 中的字符串。""actor":""login:"

到目前为止我所拥有的:

zgrep -e '"type":"FollowEvent"' /path/to/dir/* | zgrep -o '"actor":(?!{)*' | cut -f2- -d: | cut -d',' -f1 > results_file.txt

编辑:这zgrep是做什么的:

对于 /path/to/dir 中的所有文件,对于包含"type":"FollowEvent", find"actor:"后不跟有 的所有行{。然后取出 the 之后:和 next 之前的所有内容,。将结果放入results_file.txt.

编辑显示数据:

正在被 grep 的文件中的一行可能如下所示:

{"repo":{"url":"https://url","name":"/"},"type":"FollowEvent","public":true,"created_at":"2011-05-29","payload":{"target":{"gravatar_id":"73","id":64,"repos":35,"followers":58,"login":"username3"}},"actor":{"gravatar_id":"06","id":439,"url":"https://url","avatar_url":"https://.png","login":"username4"},"id":"14"}

或者像这样:

{"repo":{"url":"https://url/","name":"/"},"type":"FollowEvent","public":true,"created_at":"2011-04-01","payload":{"target":{"gravatar_id":"40","repos":2,"followers":1,"login":"username2"},"actor":"username1","actor_gravatar":"de4"},"actor":{"gravatar_id":"de4","id":716,"url":"https://url","avatar_url":"https://.png","login":"username2"},"id":"12"}

答案1

可以使用以下命令从两个 JSON 文档中获取login下面列出的用户名:targetjq

$ jq -r '.payload.target.login' file1.json
username3

同样,可以有login以下内容:actor

$ jq -r '.actor.login' file1.json
username4

如果您想让输出以 为条件(如果不是,type则不产生任何内容):typeFollowEvent

jq -r 'select(.type == "FollowEvent") | .actor.login' file1.json

相关内容