2

I want to get the head as in my output.

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

And the filtered line:

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

What i expect to get is as below two lines:

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

How to get the two lines(head+filtered content) as output with a simple command?

3 Answers3

4

For compound conditions you use awk, not grep:

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

Note the idiomatic use of [o] in @Cyrus and my answers so that the regexp doesn't match on this command itself so you don't need to explicitly remove this command name from with regexp.

Ed Morton
  • 188,023
  • 17
  • 78
  • 185
2
ps lax | grep -e '^F' -e '[o]penbox'

or

ps lax | grep '^F\|[o]penbox'
Cyrus
  • 84,225
  • 14
  • 89
  • 153
  • IMHO it is a bit restrictive to distinguish the first line by some of its contents (in this case matching an 'F' at the beginning). For instance, ```ps``` output and columns varies greatly from a system to another, or even by our own selection of columns. I'd suggest going for a more general solution. – Ramón Gil Moreno Jun 12 '18 at 10:01
  • Thanks for the tip. The following circumvents the problem because the first line does not begin with a number: `ps lax | grep '^[^0-9]\|[o]penbox` – Cyrus Jun 13 '18 at 05:10
1

Ed's answer using awk plus the NR==1 condition is the best solution.

For completeness, let me show the use of tee and processs substitution with >(command).

For instance: to display current processes (with ps) other than bash while retaining the ps header line, use tee in the following way:

$ 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
$

Here tee redirects the output to two processes:

  • one to display the first line (first sed -n 1p),
  • then other that filters the first line (the other sed 1d) and does an additional filtering with grep.

Finally, to prevent tee from dumping the original ps output, stdout is redirected to /dev/null