0

What I want is printing the output the first line ( table head ) of ps aux and the grep result.

After search, I come up with following.

ps aux | tee >(head -1 > /dev/tty) | grep mongo

But I find the stdin of grep mongo is cut off.

Also, if I omit > /dev/tty, what will the stdout of head -1 direct to? Why isn't it the console?

(Yes, I know I can achive my purpose by command awk. I am just curious about why my command doesn't work?)

4
  • This doesn't appear to be a dupe of the question it was closed as a dupe of. This one is asking why something doesn't work as expected, The other is asking how to accomplish a specific task. Dec 22, 2014 at 15:34
  • 1
    Take a look at Thor's answer to the other question; he covers why your approach doesn't work, and a way to make it (somewhat) work. (I don't blame you for missing it, it's nowhere near the top. I missed it myself at first, too.)
    – derobert
    Dec 22, 2014 at 15:37
  • Also see a followup asked about that: How do I use tee to redirect to grep?
    – derobert
    Dec 22, 2014 at 15:40
  • Thanks @derobert the two links solve my question. I think I have more specific keyword to search to understand it.
    – Sisyphus
    Dec 23, 2014 at 5:25

1 Answer 1

0

You could use awk to match two things at the same time:

  • The first line.
  • The line containing "mongo".

There you go:

$ ps aux | awk 'NR == 1 || /mongo/ {print $0}'
  • The NR == 1 condition matches the first line.
  • The /mongo/ condition matches lines containing "mongo".
  • {print $0} is the action associated with the two previous conditions, in this case: print the whole line.

Not the answer you're looking for? Browse other questions tagged .