Csv

解析逗號分隔的字元串,忽略引號之間的逗號

  • November 9, 2021

我有一個逗號分隔的字元串,它可以包含帶逗號的引用元素。例如:

issuer=C = US, O = "DigiCert, Inc.", CN = DigiCert High Assurance TLS Hybrid ECC SHA256 2020 CA1

我想提取不同的元素,忽略引號 ( DigiCert, Inc.)。

該腳本應符合 POSIX 並在非 GNU 系統上執行。

鑑於您不想要一個通用的解決方案,即您正在尋找一個 hack 並且不想要一個強大的解決方案,這似乎非常 hack-ish 並且產生了正確的輸出,至少如果您提供的範例輸入是您可以合理遇到的最複雜的情況:

#!/usr/bin/env bash

set -o posix

grep '^[[:blank:]]*Issuer:' |
sed -Ee 's/^.* O[[:blank:]]*=[[:blank:]]*("[^"]*"|[^",]*),.*/\1/'

即使作為一個黑客,我敢肯定,如果有需要的話,這可以得到改進。

以上幾乎是 POSIX 兼容的,並且在我的非 GNU 系統上執行。

$ grep -w Issuer: /usr/local/etc/ssl/cert.pem | head -5; \
   echo '...'; grep -w Issuer: /usr/local/etc/ssl/cert.pem | tail -5
       Issuer: C = ES, O = FNMT-RCM, OU = AC RAIZ FNMT-RCM
       Issuer: C = ES, O = FNMT-RCM, OU = Ceres, organizationIdentifier = VATES-Q2826004J, CN = AC RAIZ FNMT-RCM SERVIDORES SEGUROS
       Issuer: CN = ACCVRAIZ1, OU = PKIACCV, O = ACCV, C = ES
       Issuer: C = IT, L = Milan, O = Actalis S.p.A./03358520967, CN = Actalis Authentication Root CA
       Issuer: C = US, O = AffirmTrust, CN = AffirmTrust Commercial
...
       Issuer: C = US, ST = New Jersey, L = Jersey City, O = The USERTRUST Network, CN = USERTrust ECC Certification Authority
       Issuer: C = US, ST = New Jersey, L = Jersey City, O = The USERTRUST Network, CN = USERTrust RSA Certification Authority
       Issuer: C = US, O = "VeriSign, Inc.", OU = VeriSign Trust Network, OU = "(c) 1999 VeriSign, Inc. - For authorized use only", CN = VeriSign Class 1 Public Primary Certification Authority - G3
       Issuer: C = US, O = "VeriSign, Inc.", OU = VeriSign Trust Network, OU = "(c) 1999 VeriSign, Inc. - For authorized use only", CN = VeriSign Class 2 Public Primary Certification Authority - G3
       Issuer: C = US, OU = www.xrampsecurity.com, O = XRamp Security Services Inc, CN = XRamp Global Certification Authority
$ ./test.sh < /usr/local/etc/ssl/cert.pem | head -5; \
   echo '...'; ./test.sh < /usr/local/etc/ssl/cert.pem | tail -5
FNMT-RCM
FNMT-RCM
ACCV
Actalis S.p.A./03358520967
AffirmTrust
...
The USERTRUST Network
The USERTRUST Network
"VeriSign, Inc."
"VeriSign, Inc."
XRamp Security Services Inc

引用自:https://unix.stackexchange.com/questions/676776