如何用grep或AWK提取指定前置行后的目标输出行?
提取命令输出中特定前置行后的目标行
我有一条命令会输出大量内容,仅需提取其中一行。该行内容不固定,但它的前两行内容始终固定。如何通过搜索这些固定的前置行来提取目标行?
命令输出示例:
foo-bar blahblah =============== foo bar foo bar foo bar. this string is always the same (search string) =============== the desired line is here ========== foofoofoo ==========
我已尝试执行以下命令,但去掉if语句后仍无法正常工作:
awk '/this string is always the same/{p=1} NF{out=$2} END{if(p==1){print out}}'
期望得到的结果为:
the desired line is here
解决方案
可以通过awk精准定位固定前置行,再捕获目标内容,以下是两种实用写法:
方法1:简洁版awk命令
awk '/this string is always the same/{getline; getline; sub(/^[[:space:]]+/,""); print}'
/this string is always the same/:匹配固定的搜索行- 连续两次
getline:跳过搜索行后的等号分隔线,直接读取目标行 sub(/^[[:space:]]+/,""):移除目标行开头的空格print:输出处理后的目标内容
方法2:健壮版awk命令(适配格式变动)
如果输出中可能存在空行或分隔线格式微调,用状态标记的写法更可靠:
awk ' /this string is always the same/ { state=1; next } state == 1 && /^[[:space:]]*={3,}/ { state=2; next } state == 2 && NF { sub(/^[[:space:]]+/,""); print; exit } '
- 匹配到固定搜索行时,设置状态为1并跳过当前行
- 状态为1时,匹配到至少3个等号的分隔线,设置状态为2并跳过当前行
- 状态为2时,遇到非空行就移除开头空格并打印,随后退出(避免输出后续无关内容)
内容的提问来源于stack exchange,提问作者ehsan khodadadi
相关产品推荐
相关产品推荐

