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

相關內容