How do I filter a stream / pipeline to remove headers for empty sections?

data example from ps aux as followings. There is a newline between each section.

com-1
USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND

com-2
USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
testuser   5915  0.0  0.0 108604  2036 pts/0    S+   Jul19   0:00 -bash

com-3
USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND

com-4
USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND

com-5
USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
tuser2   2531  0.0  0.0 108604  2036 pts/0    S+   Jul19   0:00 -bash
wuser1   3591  0.0  0.0 108604  2036 pts/0    S+   Jul19   0:00 python

How to use linux shell pipe to output only the follows? There is no useful infomation for com-1, com-3 and com-4, so only the following is needed.

com-2
USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
testuser   5915  0.0  0.0 108604  2036 pts/0    S+   Jul19   0:00 -bash

com-5
USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
tuser2   2531  0.0  0.0 108604  2036 pts/0    S+   Jul19   0:00 -bash
wuser1   3591  0.0  0.0 108604  2036 pts/0    S+   Jul19   0:00 python
#!/usr/bin/env bash

headers=( )
headers_printed=0
consecutive_newlines=0

while read -r line; do
  if [[ $line ]]; then
    if (( ${#headers[@]} < 2 )); then
      # header not filled out yet, that means we're one.
      headers+=( "$line" )
      continue
    else
      # headers are filled out, and we still have more data
      consecutive_newlines=0
      if (( headers_printed )); then
        # already printed the headers, so just print our one line
        printf '%sn' "$line"
      else
        printf '%sn' "${headers[@]}" "$line"
        headers_printed=1
      fi
    fi
  else
    headers=( )
    headers_printed=0
    if (( consecutive_newlines++ == 0 )); then
      printf 'n'
    fi
  fi
done
Hello, buddy!稿源:Hello, buddy! (源链) | 关于 | 阅读提示

本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 综合编程 » How do I filter a stream &sol; pipeline to remove headers for empty sections&quest;

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录