【问题标题】:Formatting grep output with blank line between two occurrences在两次出现之间使用空行格式化 grep 输出
【发布时间】:2021-11-14 07:25:34
【问题描述】:

我希望以这种方式格式化我的输出,但使用适当、更优雅的代码。

在文件中:

line with foo occurence
line with foo occurence
line with bar occurence
line with bar occurence
line with foo occurence
line with foo occurence

我的 bash 命令:

cat file | grep -e foo && printf '\n' && cat file | grep -e bar

结果:

line with foo occurence
line with foo occurence
line with foo occurence
line with foo occurence

line with bar occurence
line with bar occurence

【问题讨论】:

  • sed: sed -n '/foo/p; /bar/H; ${g; p}' file
  • 不错的@Cyrus ;-) 有一天我应该学习如何真正使用sed 循环和缓冲区

标签: bash grep


【解决方案1】:

你可以用grep试试这个paste命令

paste -zd'\n' <(grep 'foo' input_file) <(grep 'bar' input_file)
line with foo occurence
line with foo occurence
line with foo occurence
line with foo occurence

line with bar occurence
line with bar occurence

【讨论】:

  • 不错的方法!唯一的问题是输出末尾包含一个空字节。
【解决方案2】:

如何循环运行grep 命令:

for term in foo bar
do
    grep $term file
    echo  # Add a blank line
done

以上为单行:

for term in foo bar; do grep $term file; echo; done

【讨论】:

  • 我怀疑输出的末尾有一个空行。
  • 是的,输出将在末尾包含一个空行。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-10-01
  • 2021-10-29
  • 1970-01-01
  • 2022-01-17
  • 2016-10-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多