Bash脚本回参考

问题描述

尝试通过以下示例文件中的bash shell模式匹配,仅拾取62f0fac3-8b19-49de-866b-5f5cf23f2f9f和bd23d38d-8833-4fc4-b6c0-3906df0ed161。该文件具有单行文本,其中包含许多此类模式。

尝试回参考grep和sed。似乎没有任何工作。任何帮助都将不胜感激。

"type": "Primary","id": "418bf692-4f20-4597-b624-5a7242b82379","expireIn": {"count": 0,"unit": "hours"}}],"copyModel": "ARCHIVE","id": "6f2d6bc6-f67c-41b8-b11a-b5a59d7a6ac3"}],"id": "62f0fac3-8b19-49de-866b-5f5cf23f2f9f","createdAt": "2020-08-11T17:33:45.754863Z","name": "Susanta Copy Policy"},"locked": false,"type": "Primary","id": "ca85d285-8b73-42ec-aab1-c4d13572db94","expireIn": {"count": 61,"unit": "days"}}],"advancedOptions": {"targetConnectivity": "Auto"},"id": "f61e67a4-eea6-4922-9cc1-491a5429b199"}],"id": "bd23d38d-8833-4fc4-b6c0-3906df0ed161","createdAt": "2020-07-14T19:01:33.202434Z","name": "App Gold Policy"},"locked": false
#
#
# cat test | grep -E '\"id\": \"(.*)\",\"createdAt\": \"'
"type": "Primary","locked": false
#
# cat test | grep -E '\"id\": \"(.*)\",\"createdAt\": \"\1'
#
# cat test | sed -E 's/\"id\"(.*)\"\,\"createdAt\": \"/\1/'
"type": "Primary",: "418bf692-4f20-4597-b624-5a7242b82379","id": "bd23d38d-8833-4fc4-b6c0-3906df0ed1612020-07-14T19:01:33.202434Z","locked": false
#```

解决方法

要使其与grep一起使用,您需要使用-P选项来使用Perl语法。选项-o将仅打印匹配行的匹配(非空)部分,每个这样的部分都在单独的输出行上。

然后,您可以进行负向前瞻和非贪婪匹配(此处已作了充分说明:Shortest match in regex from end)。另外,要仅显示表达式的ID部分,您可以包括环视断言以删除grep输出的一部分(在此处进行解释:https://unix.stackexchange.com/questions/13466/can-grep-output-only-specified-groupings-that-match)。

将所有内容放在一起,下面的正则表达式匹配从"id": "","createdAt"的所有内容,并断言所需的“内部”匹配不包含模式"id"本身(这就是我了解您想要的内容),并且仅返回所有“内部”匹配项,每个匹配项均位于单独的行中:

cat test | grep -Po '(?<=\"id\"\: \")((?:(?!\"id\").)*?)(?=\",\"createdAt)'

将返回

62f0fac3-8b19-49de-866b-5f5cf23f2f9f
bd23d38d-8833-4fc4-b6c0-3906df0ed161
,

谢谢伙计。我也找到了另一个替代解决方案。但是你的更好


# cat test2 | awk -F"\",\"createdAt\": " '{for(i=1;i<=NF-1;i++)printf $i "\n" }' | while read id; do echo ${id: -36}; done
62f0fac3-8b19-49de-866b-5f5cf23f2f9f
bd23d38d-8833-4fc4-b6c0-3906df0ed161
cf4464cc-3ef7-4852-a4a0-2771538f6866
fbe16f4e-8f1c-4ffd-9d5e-86b2d2d419fb
36beae3e-208a-489e-a8ea-03f9c3e2de1b
386a08c3-35e6-4469-8b3a-7b49fd09da21
# cat test2  | grep -Po '(?<=\"id\"\: \")((?:(?!\"id\").)*?)(?=\",\"createdAt)'
62f0fac3-8b19-49de-866b-5f5cf23f2f9f
bd23d38d-8833-4fc4-b6c0-3906df0ed161
cf4464cc-3ef7-4852-a4a0-2771538f6866
fbe16f4e-8f1c-4ffd-9d5e-86b2d2d419fb
36beae3e-208a-489e-a8ea-03f9c3e2de1b
386a08c3-35e6-4469-8b3a-7b49fd09da21
#```

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...