![sed를 사용하여 컬 응답 구문 분석](https://linux55.com/image/172743/sed%EB%A5%BC%20%EC%82%AC%EC%9A%A9%ED%95%98%EC%97%AC%20%EC%BB%AC%20%EC%9D%91%EB%8B%B5%20%EA%B5%AC%EB%AC%B8%20%EB%B6%84%EC%84%9D.png)
curl
macOS에서 다음 명령을 사용하여 JSON API를 호출하려고 합니다 .
curl https://api.ipify.org?format=json
다음과 같은 내용을 반환합니다.
{"ip":"xxx.xxx.xxx.xxx"}
이 응답에서 IP 주소를 추출하고 curl
이를 사용하여 다른 명령을 실행하고 싶습니다.
curl https://api.ipify.org?format=json | curl http://my.api.com?query=<IP RESULT>
sed
실패한 시도 중 일부에는 정규식을 사용한 명령을 통한 결과 파이핑이 포함되었습니다.
답변1
curl 'https://api.ipify.org?format=json' | jq -r '.ip'
이는 JSON 응답에서 최상위 키와 jq
연관된 값을 추출하는 데 사용됩니다.ip
curl
그런 다음 이를 사용하여 다른 전화를 걸 수 있습니다 curl
.
ipaddr=$( curl 'https://api.ipify.org?format=json' | jq -r '.ip' )
curl "http://my.api.com?query=$ipaddr"
또한 URL에는 쉘이 특별히 처리할 기타 문자가 ?
포함될 수 있으므로 명령줄에서 항상 인용해야 합니다 .&
jq
합격할 수 있다스스로 만든macOS에서.
아니면 할 수 있습니다.pLumo가 의견에서 제안했듯이, JSON 형식의 응답을 요청하지 마세요 api.ipfy.org
.
ipaddr=( curl 'https://api.ipify.org' )
curl "http://my.api.com?query=$ipaddr"
답변2
파이프 대신 명령 대체를 사용합니다. Linux 시스템에서는 다음을 사용합니다.
curl "http://my.api.com?query=$(curl https://api.ipify.org?format=json | grep -oP 'ip":"\K[0-9.]+')"
GNU 도구가 없는 시스템(예: macOS)에서는 다음 중 하나를 사용할 수 있습니다.
curl "http://my.api.com?query=$(curl https://api.ipify.org?format=json | sed -E 's/.*ip":"([0-9.]+).*/\1/')"
심지어
curl "http://my.api.com?query=$(curl https://api.ipify.org?format=json 2>/dev/null | tr -d '"' | sed 's/.*ip:\([0-9.]*\).*/\1/')"