如何从终端输出中获取一部分?

时间:2012-02-03 04:04:40

标签: shell

如果我运行程序,它将在终端屏幕上显示以下内容

Total Events Processed                                  799992
Events Aborted (part of RBs)                                 0
Events Rolled Back                                           0
Efficiency                                              100.00 %
Total Remote (shared mem) Events Processed                   0
Percent Remote Events                                     0.00 %
Total Remote (network) Events Processed                      0
Percent Remote Events                                     0.00 %

Total Roll Backs                                             0
Primary Roll Backs                                           0
Secondary Roll Backs                                         0
Fossil Collect Attempts                                      0
Total GVT Computations                                       0

Net Events Processed                                    799992
Event Rate (events/sec)                              3987042.0

如果我想从输出中取第一行和第五行,那我该怎么做?

3 个答案:

答案 0 :(得分:1)

如果grep实用程序可用,您可以使用它:

$ ./program | grep 'Total Events Processed\|Total Remote (shared mem) Events Processed'

答案 1 :(得分:1)

我认为sed会这样做,例如:

sed -n -e 1p -e 5p input.txt

答案 2 :(得分:0)

你也可以用awk做到这一点:

awk 'NR==1 || NR==5 {print;} NR==6 {nextfile;}'

或者更漂亮的sed:

sed -ne '1p;5p;6q'

或者甚至通过纯粹的Bourne shell脚本进行管道传输,如果这是您的滚动方式(根据您的标记):

#!/bin/sh
n=0
while read line; do
  n=$((n+1))
  if [ $n = 1 -o $n = 5 ]; then
    echo "$line"
  elif [ $n = 6 ]; then
    break
  fi
done

请注意,在所有情况下,我们都会在记录6处退出,因为无需继续遍历输出。