如何将文本放在引号中? (获取引号中 Set-Cookie header 的值)

How to put text in quotes? (Get the value of the Set-Cookie header in quotes)

我有以下命令,它给出了 Set-Cookie header 的值:

curl --head http://www.whosebug.com | sed -n "/^Set-Cookie:/p" | cut -c 13-

输出:

prov=abed7528-7639-e2e3-39a0-361a6d3f7925; domain=.whosebug.com; expires=Fri, 01-Jan-2055 00:00:00 GMT; path=/; HttpOnly

我需要用引号括起这个输出,像这样:

"prov=abed7528-7639-e2e3-39a0-361a6d3f7925; domain=.whosebug.com; expires=Fri, 01-Jan-2055 00:00:00 GMT; path=/; HttpOnly"

如果您的输入是单行,将其通过管道输入 sed 's/\(.*\)/""/' 应该可以解决问题。

如果您的文本跨越多行,则此方法无效,但以下方法有效:

… | { printf \"; cat; echo \"; }

... 但是,这将保留所有换行符,这也可能是不可取的。要取消最后一个换行符,请改用以下内容:

… | { printf \"; sed '$s/$/"/'; }

或者,作为单个 sed 命令:

… | sed '1s/^/"/; $s/$/"/'

使用 printf

printf '"%s"\n' "$(curl ...)"

命令替换去除所有尾随换行符,因此结束引号将在同一行。

但是尾部有回车return(网络流量一般使用\r\n行尾)。将其添加到管道的末尾

| tr -d '\r'
# or
| sed 's/\r$//'

将管道合并为一个 sed 命令:

curl -s --head http://www.whosebug.com | sed -En '/^Set-Cookie:/ {
    s/^.{12}/"/
    s/\r$/"/
    p
    q
}'