如何通过管道在grep之后使用if语句

时间:2019-06-07 19:18:25

标签: bash

我正在尝试查找"type":"FollowEvent"的所有实例,然后在这些实例中,如果字符串"actor":后没有{,则捕获{{1 }}紧接"之后。否则,捕获"actor":之后紧跟的"中包含的字符串。

到目前为止我所拥有的:

"login:"

这是什么:

对于/ path / to / dir中的所有文件,对于包含zgrep -e '"type":"FollowEvent"' /path/to/dir/* | zgrep -o '"actor":(?!{)*' | cut -f2- -d: | cut -d',' -f1 > results_file.txt 的所有行,请找到"type":"FollowEvent",而不是"actor:"。然后在{之后和下一个:之前进行所有操作。将结果放入,

要进行grep的文件中的一行可能看起来像这样:

results_file.txt

或类似这样:

{"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"}

我想要什么:

仅包含actor用户名的文件。在这里,我想要在{"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"} 中:

results_file.txt

1 个答案:

答案 0 :(得分:1)

让我们说:

JSON='{"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"}'

对于一个简单的答案,我建议您使用jqhttps://stedolan.github.io/jq/

$ echo "$JSON" | jq -r '. | select(.type=="FollowEvent") | .actor.login'
username4

您可以使用默认的程序包管理器在大多数发行版中安装它。

无论如何,如果您需要使用GNU工具。

$ echo "$JSON" | grep '"type":"FollowEvent"' | sed 's/.*"login":"\([^"]*\).*/\1/g'
username4