【问题标题】:How to display all line before and after string matches until blank line detected in shell如何在字符串匹配之前和之后显示所有行,直到在 shell 中检测到空行
【发布时间】:2022-10-25 14:36:38
【问题描述】:

我需要帮助grep 一个包含大量数据的文件。我有一个带有以下行的文件:

random line with hashcode 1
This file is use for some analysis
Analysis code is <01234>
This is line after analysis

This is second test line
This file is use for some analysis
Analysis code is <01234>
This is line after analysis

Some data to be here as well 
This file is use for some analysis
Analysis code is <01267>
This is line after analysis

我只想打印那些具有字符串“分析代码”且值为“01234”的行,并打印它之前和之后的所有行。 我试图半途而废,但需要完整的逻辑。

egrep -i "Analysis code" c.txt |
grep -i 01234 |
awk -F "<" '{print $2}' |
awk -F ">" '{print $1}' |
uniq > am.txt
while read line ; do
    echo $line
    awk "/$line/,/$^/" c.txt
done <am.txt

在此之后,我只从具有分析代码的行开始获得输出。

我想打印匹配字符串之前的所有行,直到空白行出现在顶部:

random line with hashcode 1
This file is use for some analysis
Analysis code is <01234>
This is line after analysis

This is second test line
This file is use for some analysis
Analysis code is <01234>
This is line after analysis

【问题讨论】:

  • 怎么样:awk -v RS="" -v ORS="\n\n" -v IGNORECASE=1 '/analysis code/ &amp;&amp; /01234/' am.txt
  • 谢谢tshiono。它奏效了,这就是我正在寻找的。你拯救了我的一天。

标签: bash unix


【解决方案1】:

最简单的方法是使用 grep 选项在匹配行之前和之后打印行:

    grep c.txt -e "Analysis code.*<01234>" -B1 -A2

如果要打印由空行分隔的段落,可以使用多行模式或 awk,如下所示:

awk -v RS='' '/Analysis code.*&lt;01234&gt;/' c.txt

【讨论】:

  • 你的意思是大写的-A-B
  • 你是对的@tripleee。已修复,谢谢
猜你喜欢
  • 2021-04-17
  • 2021-04-03
  • 2021-06-16
  • 2014-10-07
  • 2023-02-24
  • 2018-03-24
  • 2020-08-26
  • 2022-01-20
  • 1970-01-01
相关资源
最近更新 更多