如何使用简单的命令将两行(head + filtered content)作为输出?

时间:2018-06-12 02:45:58

标签: bash grep

我想在输出中得到头部。

ps  lax |head -n 1
F   UID   PID  PPID PRI  NI    VSZ   RSS WCHAN  STAT TTY        TIME COMMAND

过滤后的行:

ps  lax |grep openbox |grep -v grep
0  1000  1608  1513  20   0 206408 20580 SyS_po S    ?          0:00 openbox --config-file /home/debian9/.config/openbox/lxde-rc.xml

我期望得到的是以下两行:

F   UID   PID  PPID PRI  NI    VSZ   RSS WCHAN  STAT TTY        TIME COMMAND
0  1000  1608  1513  20   0 206408 20580 SyS_po S    ?          0:00 openbox --config-file /home/debian9/.config/openbox/lxde-rc.xml

如何使用简单的命令将两行(head + filtered content)作为输出?

4 个答案:

答案 0 :(得分:4)

对于复合条件,您使用awk,而不是grep:

ps  lax | awk 'NR==1 || /[o]penbox/'

请注意@Cyrus中[o]的惯用语和我的答案,以便正则表达式与此命令本身不匹配,因此您无需使用regexp显式删除此命令名。

答案 1 :(得分:2)

ps lax | grep -e '^F' -e '[o]penbox'

ps lax | grep '^F\|[o]penbox'

答案 2 :(得分:1)

使用tee,然后processs substitution使用>(command)

例如:要在保留ps标题行的同时显示 bash 以外的当前进程(ps),请按以下方式使用tee

$ ps | tee >(sed -n 1p) >(sed 1d | grep -v bash) > /dev/null
      PID    PPID    PGID     WINPID   TTY         UID    STIME COMMAND
     5782    2514    3792       1940  cons2    1415878 12:21:38 /usr/bin/ps
     9998       2    9708       9708  ?        1415878 12:38:41 /usr/bin/ssh-agent
$

此处tee将输出重定向到两个进程:

  • 一个显示第一行(第一个sed -n 1p),
  • 然后其他过滤第一行(另一个sed 1d)并使用grep进行额外过滤。

最后,为防止tee转储原始ps输出,stdout会重定向到/dev/null

答案 3 :(得分:-1)

布兰登米勒的回答。

 printf  "$( ps  lax |head -n 1 )\n$( ps  lax |grep openbox |grep -v grep )"

输出:

printf  "$( ps  lax |head -n 1 )\n$( ps  lax |grep openbox |grep -v grep )"
F   UID   PID  PPID PRI  NI    VSZ   RSS WCHAN  STAT TTY        TIME COMMAND
0  1000  1608  1513  20   0 206560 20840 SyS_po S    ?          0:01 openbox --config-file /home/debian9/.config/openbox/lxde-rc.xmldebian9@hwy:~$ 

根据Brandon Miller和Ed Morton的回答取得进展。

 printf  "$( ps  lax |head -n 1 )\n$( ps  lax |grep [o]penbox )\n"

输出:

printf  "$( ps  lax |head -n 1 )\n$( ps  lax |grep openbox |grep -v grep )"
F   UID   PID  PPID PRI  NI    VSZ   RSS WCHAN  STAT TTY        TIME COMMAND
0  1000  1608  1513  20   0 206560 20840 SyS_po S    ?          0:01 openbox --config-file /home/debian9/.config/openbox/lxde-rc.xml
debian9@hwy:~$
相关问题