Background: sometimes I use ps aux | grep process_name to figure out some statistics of a process. But I can’t remember the headers of ps output. So I need to do:
ps aux | tee 1.txt | grep process_name > 2.txt
cat 1.txt | head -1 | cat - 2.txt
So my questions is: is there a way to achieve this without the two temporary files, and preferably use one line of commands instead of two lines?
The simplest way is just to use something a bit smarter than
grep. For example:will print the first line of
ps aux‘s output, plus any line that matchesprocess_name(which is a Perl regular expression — more powerful than POSIX BRE’s, and therefore more complicated, but I don’t think you’ll find any surprises if you’re just searching for a process name).Edited to add: For that matter, since
ps aux‘s headers are unlikely to change between runs, you could write:though I don’t know if that still counts as “one line of commands”. 🙂
More options: Since you don’t like the above, here are some more. This one will read and print the first line directly, and then leave the rest for
grepto read and process:This one will cause every line to be written both to standard output (file descriptor
1) and to a custom file descriptor (3); thenheadgets standard output, whilegrepgets what was written to the custom file descriptor:That one is the most general way that I know of to do what you’re asking for — at least, using only Bash builtins and features — but as you can see, it’s quite unwieldy, which is why I recommend the simpler ways when you don’t need the full power of this approach. Also, that last one no longer guarantees that headers come first; on my system, the output of
headseems to consistently end up after the output ofgrep. (I suppose that could be addressed by swapping the positions of theheadandgrepcommands, but that still wouldn’t be reliable so far as I know, and it seemed to have weird effects when I tried it just now.)