如何在Bash命令行中使用grep捕获特定文本?

时间:2019-06-02 17:51:43

标签: json regex bash command-line grep

我需要在Bash命令行上使用grep捕获特定的字符串。我不能使用sudo install / apt-install来安装任何附加软件/软件包,例如jq。我没有使用任何Python解释器;只是Bash命令行。

我在在线正则表达式测试仪上用所需的输入字符串测试了我的正则表达式字符串,并且可以正常工作。但是,当我使用grep尝试时,它会提供整个文本,而不是捕获的文本。

正则表达式:'":"(.+)","'

输入:

HTTP_RESPONSE='{"access_token":"eyJhbGciOiJSUzI1NiIsImtpZCI6IkE4M0UwQTFEQTY1MzE0NkZENUQxOTFDMzRDNTQ0RDJDODYyMzMzMzkiLCJ0eXAiOiJKV1QiLCJ4NXQiOiJxRDRLSGFaVEZHX1YwWkhEVEZSTkxJWWpNemsifQ.eyJuYmYiOjE1NTkzMjk5OTIsImV4cCI6MTU1OTMzMzU5MiwiaXNzIjoiaHR0cHM6Ly9jaW5jaHktbnByLmNsb3VkLnJlcy5ibmdmLmxvY2FsL2NpbmNoeXNzbyIsImF1ZCI6WyJodHRwczovL2NpbmNoeS1ucHIuY2xvdWQucmVzLmJuZ2YubG9jYWwvY2luY2h5c3NvL3Jlc291cmNlcyIsImpzX2FwaSJdLCJjbGllbnRfaWQiOiJhcGkiLCJzdWIiOiIxIiwiYXV0aF90aW1lIjoxNTU5MzI5OTkyLCJpZHAiOiJsb2NhbCIsInByb2ZpbGUiOiJBZG1pbmlzdHJhdG9yIiwiZW1haWwiOiJhZG1pbkBjaW5jaHkuY28iLCJyb2xlIjoiQ2luY2h5IFVzZXIgQWNjb3VudCIsImlkIjoiYWRtaW4iLCJzY29wZSI6WyJqc19hcGkiXSwiYW1yIjpbImN1c3RvbSJdfQ.gI_MYzkanGmDXPd8Wp1Q2XOOhAvnWxzOxSUngxYv8UFO1ozXm5ZxFDpUVXFodTQHKEk2B9h9VMXwyg80bxqqT7csHnjg43tylgEIKpupcubqXT1HzH_bMv8povGU6S75b8p8SWQKyYihm4nBdMDJFZMtKMg95ByB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frlARB46ukB3tBJzNvMDvxi44wfwpnky-4dxq0CcHoa766l6E66gjaLmR3ApHy4YKnP_DxDSR6mSHnVTEzPN7mt_1rklseK0TVd0kK3CpUg2aQ

1 个答案:

答案 0 :(得分:0)

如果没有更合适的工具(例如jq),则使用GNU grep和与Perl兼容的正则表达式(PCRE):

echo "$HTTP_RESPONSE" | grep -oP '(?<="access_token":").*?(?=")'