这里 - How to parse HTTP headers using Bash?有一个非常优雅的解决方案可以在没有 awk 的情况下在 bash 中进行解析:
shopt -s extglob # Required to trim whitespace; see below
while IFS=':' read key value; do
# trim whitespace in "value"
value=${value##+([[:space:]])}; value=${value%%+([[:space:]])}
case "$key" in
Server) SERVER="$value"
;;
Content-Type) CT="$value"
;;
HTTP*) read PROTO STATUS MSG <<< "$key{$value:+:$value}"
;;
esac
done < <(curl -sI http://www.google.com)
echo $STATUS
echo $SERVER
echo $CT
但是如何将其转换为纯 sh 呢?
我也打算使用 wget 而不是 curl,但似乎我可以处理。
最佳答案
您可以通过在此处文档中使用 read
来修剪空格。使用命名管道“模拟”进程替换。 (进程替换实际上可以在某些操作系统上使用命名管道实现。)
mkfifo headers
curl -sI http://www.google.com > headers &
{
# This line is guaranteed to be first, before any headers.
# Read it separately.
read -r PROTO STATUS MSG
while IFS=':' read -r key value; do
# trim whitespace in "value"
read -r value <<EOF
$value
EOF
case $key in
Server) SERVER="$value"
;;
Content-Type) CT="$value"
;;
esac
done
} < headers
rm headers
我把它留作练习,研究如何正确缩进此处文档的正文。
关于linux - 如何通过/bin/sh解析HTTP头?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39819547/