Shell script - Find and copy a string in text file

时间:2018-03-25 21:15:14

标签: bash shell

I have a json file:

[{"outputType":{"type":"APK"},"apkInfo":{"type":"MAIN","splits":[],"versionCode":1},"path":"app-debug.apk","properties":{"packageId":"com.abc.def","split":"","minSdkVersion":"17"}}]

I want to use shell script to find the packageID (com.abc.def in this case) and copy it to a variable. I don't really care about how it's done, as long as I get a variable holding the string, that will be perfect.

I don't do much shell script, but this task requires me to use shell script.

Thanks in advance.

2 个答案:

答案 0 :(得分:0)

v=$(sed -r 's/.*"packageId":"([^"]+)".*/\1/' file.json)

查找带有冒号和引号的键“packageId”,抓取任何不是引号的内容,然后是引号。 \ 1是对圆形parens中匹配表达式的引用。

答案 1 :(得分:0)

使用像 jq 这样的工具来处理JSON并且不要依赖shell脚本丑陋的黑客攻击。

在您的情况下,它将是:label

使用解析JSON的工具更容易,更易读,更安全。