[英]Extract string between newline and variable data in Bash
As part of a load test, I've a file with a generated list of requests. 作为负载测试的一部分,我有一个包含生成的请求列表的文件。 The format is below, in that, the payload is in between two newline characters; 格式如下,因为有效负载在两个换行符之间; the GET indicating the start of a new request. 表示新请求开始的GET。 I would like to extract only the payload. 我只想提取有效载荷。
Connection: false
Content-Length: 25
foo=bar1&foo2=bar2
GET http://localhost:1080/dasistgut
I have tried several combinations without success: 我尝试了几种组合,但均未成功:
grep -zoP "(?<=(\n)).*(?<=(\GET))" sample.txt
grep -zoP "(?<=(\n)).*(?<=(\n))" sample.txt
grep -zoP "(?<=(\n)).*(?<=\n)" sample.txt
Expected output: foo=bar1&foo2=bar2
预期输出: foo=bar1&foo2=bar2
You may use this gnu grep
: 您可以使用以下gnu grep
:
var=$(grep -zoP '.+(?=\R{2}GET )' file)
echo "$var"
foo=bar1&foo2=bar2
Lookahead assertion (?=\\R{2}GET )
makes sure that input has exact 2 newlines ( \\R
) followed by "GET "
ahead of current position. 前瞻断言(?=\\R{2}GET )
确保输入具有精确的2个换行符( \\R
),后跟当前位置之前的"GET "
。
Alternative awk
based solution: 基于awk
的替代解决方案:
awk '!NF{++n; next} n && /^GET /{print p} {p=$0; n=0}' file
foo=bar1&foo2=bar2
使用awk
匹配空白行,获取下一行并打印,然后跳过下一行(应始终为空白)。
awk '/^$/ { getline; print; getline; }' sample.text
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.