How to grep a specific line _and_ the first line of a file?

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP











up vote
74
down vote

favorite
32












Assuming a simple grep such as:



$ psa aux | grep someApp
1000 11634 51.2 0.1 32824 9112 pts/1 SN+ 13:24 7:49 someApp


This provides much information, but as the first line of the ps command is missing there is no context for the info. I would prefer that the first line of ps be shown as well:



$ psa aux | someMagic someApp
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
1000 11634 51.2 0.1 32824 9112 pts/1 SN+ 13:24 7:49 someApp


Of course, I could add a regex to grep specifically for ps:



$ ps aux | grep -E "COMMAND|someApp"


However, I would prefer a more general solution as there are other cases in which I would like to have the first line as well.



Seems like this would be a good use case for a "stdmeta" file descriptor.










share|improve this question



















  • 9




    The complexity required by these answers shows how the Unix philosophy of "do one thing and do it well" sometimes fails us when measured by the yard stick of usability: knowing all these commands well enough to apply them to this common problem (filtering process info and still seeing the column labels) shows the downside of the approach: sometimes things don't fit together very cleanly. This is why tools like ack are so useful, and why perl rocketed past sed,awk, etc. in popularity: it's important for the parts to sum up into a coherent whole.
    – iconoclast
    Sep 12 '12 at 19:56






  • 3




    of course, for this particular example, you could use the -C argument to ps and you wouldn't need to pipe it into grep. e.g. ps u -C someApp or even ps u -C app1 -C app2 -C app3
    – cas
    Sep 13 '12 at 6:06






  • 1




    @iconoclast: of course the Unixy solution would be a tool that can multiplex multiple lines each to be filtered through different set of filters. Kinda a generalized version of ps aux | head -1; grep foo; mentioned by @Nahuel Fouilleul below (his is probably the only solution that I'd be able to recall on the spot if needed)
    – Lie Ryan
    Sep 13 '12 at 17:13










  • @iconoclast: Lacking experience with, and knowledge of the tools, what the tools really do well will always seem entirely useless. Knowing a command well is no where on the yard stick of usability, it's on the yard stick of read the fine manual and practice. These tools have been around for decades. They work and fit together very nicely (and cleanly).
    – Ð¯Ñ€Ð¾ÑÐ»Ð°Ð² Рахматуллин
    Sep 15 '12 at 11:19











  • @ЯрославРахматуллин: I think you may have completely misunderstood what I said. (Perhaps because English is not your first language?) "Usability" is related to UX ("user experience") not utility (or "usefulness"). Pointing out that when a simple operation is this complex it hurts usability is NOT the same as saying the tools are useless. Quite obviously they are not useless. No one in their right mind would say they are useless.
    – iconoclast
    Sep 17 '12 at 2:47















up vote
74
down vote

favorite
32












Assuming a simple grep such as:



$ psa aux | grep someApp
1000 11634 51.2 0.1 32824 9112 pts/1 SN+ 13:24 7:49 someApp


This provides much information, but as the first line of the ps command is missing there is no context for the info. I would prefer that the first line of ps be shown as well:



$ psa aux | someMagic someApp
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
1000 11634 51.2 0.1 32824 9112 pts/1 SN+ 13:24 7:49 someApp


Of course, I could add a regex to grep specifically for ps:



$ ps aux | grep -E "COMMAND|someApp"


However, I would prefer a more general solution as there are other cases in which I would like to have the first line as well.



Seems like this would be a good use case for a "stdmeta" file descriptor.










share|improve this question



















  • 9




    The complexity required by these answers shows how the Unix philosophy of "do one thing and do it well" sometimes fails us when measured by the yard stick of usability: knowing all these commands well enough to apply them to this common problem (filtering process info and still seeing the column labels) shows the downside of the approach: sometimes things don't fit together very cleanly. This is why tools like ack are so useful, and why perl rocketed past sed,awk, etc. in popularity: it's important for the parts to sum up into a coherent whole.
    – iconoclast
    Sep 12 '12 at 19:56






  • 3




    of course, for this particular example, you could use the -C argument to ps and you wouldn't need to pipe it into grep. e.g. ps u -C someApp or even ps u -C app1 -C app2 -C app3
    – cas
    Sep 13 '12 at 6:06






  • 1




    @iconoclast: of course the Unixy solution would be a tool that can multiplex multiple lines each to be filtered through different set of filters. Kinda a generalized version of ps aux | head -1; grep foo; mentioned by @Nahuel Fouilleul below (his is probably the only solution that I'd be able to recall on the spot if needed)
    – Lie Ryan
    Sep 13 '12 at 17:13










  • @iconoclast: Lacking experience with, and knowledge of the tools, what the tools really do well will always seem entirely useless. Knowing a command well is no where on the yard stick of usability, it's on the yard stick of read the fine manual and practice. These tools have been around for decades. They work and fit together very nicely (and cleanly).
    – Ð¯Ñ€Ð¾ÑÐ»Ð°Ð² Рахматуллин
    Sep 15 '12 at 11:19











  • @ЯрославРахматуллин: I think you may have completely misunderstood what I said. (Perhaps because English is not your first language?) "Usability" is related to UX ("user experience") not utility (or "usefulness"). Pointing out that when a simple operation is this complex it hurts usability is NOT the same as saying the tools are useless. Quite obviously they are not useless. No one in their right mind would say they are useless.
    – iconoclast
    Sep 17 '12 at 2:47













up vote
74
down vote

favorite
32









up vote
74
down vote

favorite
32






32





Assuming a simple grep such as:



$ psa aux | grep someApp
1000 11634 51.2 0.1 32824 9112 pts/1 SN+ 13:24 7:49 someApp


This provides much information, but as the first line of the ps command is missing there is no context for the info. I would prefer that the first line of ps be shown as well:



$ psa aux | someMagic someApp
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
1000 11634 51.2 0.1 32824 9112 pts/1 SN+ 13:24 7:49 someApp


Of course, I could add a regex to grep specifically for ps:



$ ps aux | grep -E "COMMAND|someApp"


However, I would prefer a more general solution as there are other cases in which I would like to have the first line as well.



Seems like this would be a good use case for a "stdmeta" file descriptor.










share|improve this question















Assuming a simple grep such as:



$ psa aux | grep someApp
1000 11634 51.2 0.1 32824 9112 pts/1 SN+ 13:24 7:49 someApp


This provides much information, but as the first line of the ps command is missing there is no context for the info. I would prefer that the first line of ps be shown as well:



$ psa aux | someMagic someApp
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
1000 11634 51.2 0.1 32824 9112 pts/1 SN+ 13:24 7:49 someApp


Of course, I could add a regex to grep specifically for ps:



$ ps aux | grep -E "COMMAND|someApp"


However, I would prefer a more general solution as there are other cases in which I would like to have the first line as well.



Seems like this would be a good use case for a "stdmeta" file descriptor.







bash command-line






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited 10 hours ago

























asked Sep 12 '12 at 10:45









dotancohen

6,001175494




6,001175494







  • 9




    The complexity required by these answers shows how the Unix philosophy of "do one thing and do it well" sometimes fails us when measured by the yard stick of usability: knowing all these commands well enough to apply them to this common problem (filtering process info and still seeing the column labels) shows the downside of the approach: sometimes things don't fit together very cleanly. This is why tools like ack are so useful, and why perl rocketed past sed,awk, etc. in popularity: it's important for the parts to sum up into a coherent whole.
    – iconoclast
    Sep 12 '12 at 19:56






  • 3




    of course, for this particular example, you could use the -C argument to ps and you wouldn't need to pipe it into grep. e.g. ps u -C someApp or even ps u -C app1 -C app2 -C app3
    – cas
    Sep 13 '12 at 6:06






  • 1




    @iconoclast: of course the Unixy solution would be a tool that can multiplex multiple lines each to be filtered through different set of filters. Kinda a generalized version of ps aux | head -1; grep foo; mentioned by @Nahuel Fouilleul below (his is probably the only solution that I'd be able to recall on the spot if needed)
    – Lie Ryan
    Sep 13 '12 at 17:13










  • @iconoclast: Lacking experience with, and knowledge of the tools, what the tools really do well will always seem entirely useless. Knowing a command well is no where on the yard stick of usability, it's on the yard stick of read the fine manual and practice. These tools have been around for decades. They work and fit together very nicely (and cleanly).
    – Ð¯Ñ€Ð¾ÑÐ»Ð°Ð² Рахматуллин
    Sep 15 '12 at 11:19











  • @ЯрославРахматуллин: I think you may have completely misunderstood what I said. (Perhaps because English is not your first language?) "Usability" is related to UX ("user experience") not utility (or "usefulness"). Pointing out that when a simple operation is this complex it hurts usability is NOT the same as saying the tools are useless. Quite obviously they are not useless. No one in their right mind would say they are useless.
    – iconoclast
    Sep 17 '12 at 2:47













  • 9




    The complexity required by these answers shows how the Unix philosophy of "do one thing and do it well" sometimes fails us when measured by the yard stick of usability: knowing all these commands well enough to apply them to this common problem (filtering process info and still seeing the column labels) shows the downside of the approach: sometimes things don't fit together very cleanly. This is why tools like ack are so useful, and why perl rocketed past sed,awk, etc. in popularity: it's important for the parts to sum up into a coherent whole.
    – iconoclast
    Sep 12 '12 at 19:56






  • 3




    of course, for this particular example, you could use the -C argument to ps and you wouldn't need to pipe it into grep. e.g. ps u -C someApp or even ps u -C app1 -C app2 -C app3
    – cas
    Sep 13 '12 at 6:06






  • 1




    @iconoclast: of course the Unixy solution would be a tool that can multiplex multiple lines each to be filtered through different set of filters. Kinda a generalized version of ps aux | head -1; grep foo; mentioned by @Nahuel Fouilleul below (his is probably the only solution that I'd be able to recall on the spot if needed)
    – Lie Ryan
    Sep 13 '12 at 17:13










  • @iconoclast: Lacking experience with, and knowledge of the tools, what the tools really do well will always seem entirely useless. Knowing a command well is no where on the yard stick of usability, it's on the yard stick of read the fine manual and practice. These tools have been around for decades. They work and fit together very nicely (and cleanly).
    – Ð¯Ñ€Ð¾ÑÐ»Ð°Ð² Рахматуллин
    Sep 15 '12 at 11:19











  • @ЯрославРахматуллин: I think you may have completely misunderstood what I said. (Perhaps because English is not your first language?) "Usability" is related to UX ("user experience") not utility (or "usefulness"). Pointing out that when a simple operation is this complex it hurts usability is NOT the same as saying the tools are useless. Quite obviously they are not useless. No one in their right mind would say they are useless.
    – iconoclast
    Sep 17 '12 at 2:47








9




9




The complexity required by these answers shows how the Unix philosophy of "do one thing and do it well" sometimes fails us when measured by the yard stick of usability: knowing all these commands well enough to apply them to this common problem (filtering process info and still seeing the column labels) shows the downside of the approach: sometimes things don't fit together very cleanly. This is why tools like ack are so useful, and why perl rocketed past sed,awk, etc. in popularity: it's important for the parts to sum up into a coherent whole.
– iconoclast
Sep 12 '12 at 19:56




The complexity required by these answers shows how the Unix philosophy of "do one thing and do it well" sometimes fails us when measured by the yard stick of usability: knowing all these commands well enough to apply them to this common problem (filtering process info and still seeing the column labels) shows the downside of the approach: sometimes things don't fit together very cleanly. This is why tools like ack are so useful, and why perl rocketed past sed,awk, etc. in popularity: it's important for the parts to sum up into a coherent whole.
– iconoclast
Sep 12 '12 at 19:56




3




3




of course, for this particular example, you could use the -C argument to ps and you wouldn't need to pipe it into grep. e.g. ps u -C someApp or even ps u -C app1 -C app2 -C app3
– cas
Sep 13 '12 at 6:06




of course, for this particular example, you could use the -C argument to ps and you wouldn't need to pipe it into grep. e.g. ps u -C someApp or even ps u -C app1 -C app2 -C app3
– cas
Sep 13 '12 at 6:06




1




1




@iconoclast: of course the Unixy solution would be a tool that can multiplex multiple lines each to be filtered through different set of filters. Kinda a generalized version of ps aux | head -1; grep foo; mentioned by @Nahuel Fouilleul below (his is probably the only solution that I'd be able to recall on the spot if needed)
– Lie Ryan
Sep 13 '12 at 17:13




@iconoclast: of course the Unixy solution would be a tool that can multiplex multiple lines each to be filtered through different set of filters. Kinda a generalized version of ps aux | head -1; grep foo; mentioned by @Nahuel Fouilleul below (his is probably the only solution that I'd be able to recall on the spot if needed)
– Lie Ryan
Sep 13 '12 at 17:13












@iconoclast: Lacking experience with, and knowledge of the tools, what the tools really do well will always seem entirely useless. Knowing a command well is no where on the yard stick of usability, it's on the yard stick of read the fine manual and practice. These tools have been around for decades. They work and fit together very nicely (and cleanly).
– Ð¯Ñ€Ð¾ÑÐ»Ð°Ð² Рахматуллин
Sep 15 '12 at 11:19





@iconoclast: Lacking experience with, and knowledge of the tools, what the tools really do well will always seem entirely useless. Knowing a command well is no where on the yard stick of usability, it's on the yard stick of read the fine manual and practice. These tools have been around for decades. They work and fit together very nicely (and cleanly).
– Ð¯Ñ€Ð¾ÑÐ»Ð°Ð² Рахматуллин
Sep 15 '12 at 11:19













@ЯрославРахматуллин: I think you may have completely misunderstood what I said. (Perhaps because English is not your first language?) "Usability" is related to UX ("user experience") not utility (or "usefulness"). Pointing out that when a simple operation is this complex it hurts usability is NOT the same as saying the tools are useless. Quite obviously they are not useless. No one in their right mind would say they are useless.
– iconoclast
Sep 17 '12 at 2:47





@ЯрославРахматуллин: I think you may have completely misunderstood what I said. (Perhaps because English is not your first language?) "Usability" is related to UX ("user experience") not utility (or "usefulness"). Pointing out that when a simple operation is this complex it hurts usability is NOT the same as saying the tools are useless. Quite obviously they are not useless. No one in their right mind would say they are useless.
– iconoclast
Sep 17 '12 at 2:47











15 Answers
15






active

oldest

votes

















up vote
66
down vote



accepted










Good way



Normally you can't do this with grep but you can use other tools. AWK was already mentioned but you can also use sed, like this:



sed -e '1p' -e '/youpattern/!d'


How it works:



  1. Sed utility works on each line individually, running specified commands on each of them. You can have multiple commands, specifying several -e options. We can prepend each command with a range parameter that specifies if this command should be applied to specific line or not.


  2. "1p" is a first command. It uses p command which normally prints all the lines. But we prepend it with a numerical value that specifies the range it should be applied to. Here, we use 1 which means first line. If you want to print more lines, you can use x,yp where x is first line to print, y is last line to print. For example to print first 3 lines, you would use 1,3p


  3. Next command is d which normally deletes all the lines from buffer. Before this command we put yourpattern between two / characters. This is the other way (first was to specify which lines as we did with p command) of addressing lines that the command should be running at. This means the command will only work for the lines that match yourpattern. Except, we use ! character before d command which inverts its logic. So now it will remove all the lines that do not match specified pattern.


  4. At the end, sed will print all the lines that are left in buffer. But we removed lines that do not match from the buffer so only matching lines will be printed.


To sum up: we print 1st line, then we delete all the lines that do not match our pattern from input. Rest of the lines are printed (so only lines that do match the pattern).



First line problem



As mentioned in comments, there is a problem with this approach. If specified pattern matches also first line, it will be printed twice (once by p command and once because of a match). We can avoid this in two ways:



  1. Adding 1d command after 1p. As I already mentioned, d command deletes lines from buffer and we specify it's range by number 1, which means it will only delete 1st line. So the command would be sed -e '1p' -e '1d' -e '/youpattern/!d'


  2. Using 1b command, instead of 1p. It's a trick. b command allows us to jump to other command specified by a label (this way some commands can be omitted). But if this label is not specified (as in our example) it just jumps to the end of commands, ignoring rest of the commands for our line. So in our case, last d command won't remove this line from buffer.


Full example:



ps aux | sed -e '1b' -e '/syslog/!d'


Using semicolon



Some sed implementations can save you some typing by using semicolon to separate commands instead of using multiple -e options. So if you don't care about being portable the command would be ps aux | sed '1b;/syslog/!d'. It works at least in GNU sed and busybox implementations.



Crazy way



Here's, however, rather crazy way to do this with grep. It's definitely not optimal, I'm posting this just for learning purposes, but you may use it for example, if you don't have any other tool in your system:



ps aux | grep -n '.*' | grep -e '(^1:)|syslog'


How it works



  1. First, we use -n option to add line numbers before each line. We want to numerate all the lines we we are matching .* - anything, even empty line. As suggested in comments, we can also match '^', result is the same.


  2. Then we are using extended regular expressions so we can use | special character which works as OR. So we match if the line starts with 1: (first line) or contains our pattern (in this case its syslog).


Line numbers problem



Now the problem is, we are getting this ugly line numbers in our output. If this is a problem, we can remove them with cut, like this:



ps aux | grep -n '.*' | grep -e '(^1:)|syslog' | cut -d ':' -f2-


-d option specifies delimiter, -f specifies fields (or columns) we want to print. So we want to cut each lines on every : character and print only 2nd and all subsequent columns. This effectively removes first column with it's delimiter and this is exactly what we need.






share|improve this answer


















  • 4




    Line numbering can be done with cat -n as well and would look clearer as with a grep abused for this.
    – Alfe
    Sep 12 '12 at 13:34







  • 1




    nl does not count empty lines (but prints them without line number), cat -n formats the numbering with preceding spaces, grep -n . strips empty lines at all and adds a colon. All have their ... er ... features ;-)
    – Alfe
    Sep 12 '12 at 15:19






  • 2




    Very educational well-written answer. I tried to replace "Pretend" (Near the beginning) with "Prepend" for you but it wanted more changes and I didn't feel like changing random crap in your post, so you might want to fix that.
    – Bill K
    Sep 12 '12 at 16:57






  • 2




    ps aux | sed '1p;/pattern/!d' will print the first line twice if it matches pattern. Best is to used the b command: ps aux | sed -e 1b -e '/pattern/!d'. cat -n is not POSIX. grep -n '^' would number every line (not an issue for ps output which doesn't have empty lines). nl -ba -d $'n' numbers every line.
    – Stéphane Chazelas
    Sep 13 '12 at 9:46






  • 2




    Note that 1b;... is not portable nor POSIX, there can't be any other command after "b", so you need a newline or another -e expression.
    – Stéphane Chazelas
    Sep 18 '12 at 21:03

















up vote
57
down vote













How do you feel about using awk instead of grep?



chopper:~> ps aux | awk 'NR == 1 || /syslogd/'
USER PID %CPU %MEM VSZ RSS TT STAT STARTED TIME COMMAND
root 19 0.0 0.0 2518684 1160 ?? Ss 26Aug12 1:00.22 /usr/sbin/syslogd
mrb 574 0.0 0.0 2432852 696 s006 R+ 8:04am 0:00.00 awk NR == 1 || /syslogd/



  • NR == 1: Number of record == 1; ie. the first line


  • ||: or:


  • /syslogd/: Pattern to search for

It might also be worth looking at pgrep, although this is more for scripts rather than user-facing output. It does avoid the grep command itself from appearing in the output, though.



chopper:~> pgrep -l syslogd
19 syslogd





share|improve this answer




















  • Very nice, thanks. This is also nicely scriptable for future expansion.
    – dotancohen
    Sep 12 '12 at 14:30










  • I need to learn me some awk. very nice.
    – user606723
    Sep 13 '12 at 15:43

















up vote
29
down vote













ps aux | read line;echo "$line";grep someApp;


EDIT: after comments



ps aux | head -1;grep someApp;


I though head -1 would read all input, but after testing it, it works too.



 head -1;grep ok; <<END
this is a test
this line should be ok
not this one
END


output is



this is a test
this line should be ok





share|improve this answer


















  • 2




    That's the idea spelled out directly in bash. I'd like to give more than one thumbs-up for this. I'd just maybe use IFS='' read line; ... in case the header starts with spaces.
    – Alfe
    Sep 12 '12 at 13:31











  • This does exactly attack the problem directly. Nice!
    – dotancohen
    Sep 12 '12 at 14:36







  • 3




    I'd just use head -1 instead of the read/echo combo.
    – chepner
    Sep 12 '12 at 16:07






  • 1




    Well, it works with head -n1 on my bash. This can probably be implementation specific. My head is not reading whole input in this case, only first line, leaving rest of them in the input buffer.
    – Krzysztof Adamski
    Sep 13 '12 at 10:11






  • 2




    head -n1 is shorter, but it appears even the POSIX spec is silent as to how much of its input it is allowed to read, so perhaps read line; echo $line is more portable after all.
    – chepner
    Sep 13 '12 at 11:59

















up vote
14
down vote













Ps support internal filter,



Suppose you're looking for bash process:



ps -C bash -f



Will list all process that named bash.






share|improve this answer




















  • Thanks, that is nice to know. However, it won't find scripts started from python, among others.
    – dotancohen
    Sep 12 '12 at 14:32

















up vote
5
down vote













I tend to send the header to stderr:



ps | (IFS= read -r HEADER; echo "$HEADER" >&2; cat) | grep ps


This is usually sufficient for human reading purposes. e.g.:



 PID TTY TIME CMD
4738 pts/0 00:00:00 ps


The bracketed part could go into its own script for general use.



There's an added convenience in that the output can be further piped (to sort etc.) and the header will remain on top.






share|improve this answer



























    up vote
    5
    down vote













    You could also use tee and head:



    ps aux | tee >(head -n1) | grep syslog


    Note however that as long as tee is unable to ignore SIGPIPE signals (see e.g. the discussion here) this approach needs a workaround to be reliable. The workaround is to ignore SIGPIPE signals, this can for example be done like this in bash like shells:



    trap '' PIPE # ignore SIGPIPE
    ps aux | tee >(head -n1) 2> /dev/null | grep syslog
    trap - PIPE # restore SIGPIPE handling


    Also note that the output order is not guaranteed.






    share|improve this answer






















    • I would not rely on this to work, the first time I ran it (zsh) it produced column headers below grep results. Second time it was fine.
      – Rqomey
      Sep 12 '12 at 12:16






    • 1




      I haven't seen this yet, but one way to increase reliability is to insert a small delay in the pipeline before the grep: | sleep .5; cat .
      – Thor
      Sep 12 '12 at 12:42






    • 2




      Adding sleeps to avoid concurrency problems is always a hack. Though this might work, it's a step towards the dark side. -1 for this.
      – Alfe
      Sep 12 '12 at 13:36






    • 1




      I have had a few other strange issues while trying this answer, I set up a question to check
      – Rqomey
      Sep 12 '12 at 13:47











    • This is an interesting use of tee, but I find it unreliable and often only prints the output line, but not the header line.
      – dotancohen
      Sep 12 '12 at 14:32

















    up vote
    4
    down vote













    Perhaps two ps commands would be easiest.



    $ ps aux | head -1 && ps aux | grep someApp
    USER PID %CPU %MEM VSZ RSS TT STAT STARTED TIME COMMAND
    100 3304 0.0 0.2 2466308 6476 ?? Ss 2Sep12 0:01.75 /usr/bin/someApp





    share|improve this answer
















    • 2




      I don't like this solution, primarily because the situation could change between the first and second ps aux call... And if you just want that static first line, why not echo it manually?
      – Shadur
      Sep 12 '12 at 11:19






    • 1




      Changes between the two calls aren't to be bothered in this situation. The first will only provide the headline which will always fit to the output of the second.
      – Alfe
      Sep 12 '12 at 13:30







    • 2




      I don't see why this was downvoted, it certainly is a viable option. Upvoting.
      – dotancohen
      Sep 12 '12 at 14:37

















    up vote
    4
    down vote













    You could use pidstat with:



    pidstat -C someApp
    or
    pidstat -p <PID>


    Example:



    # pidstat -C java
    Linux 3.0.26-0.7-default (hostname) 09/12/12 _x86_64_

    13:41:21 PID %usr %system %guest %CPU CPU Command
    13:41:21 3671 0.07 0.02 0.00 0.09 1 java


    Further Info:
    http://linux.die.net/man/1/pidstat






    share|improve this answer




















    • Thanks, that is nice to know. However, it won't find scripts started from python, among others.
      – dotancohen
      Sep 12 '12 at 14:35

















    up vote
    4
    down vote













    Put the following in your .bashrc file or copy/paste in shell first, for testing.



    function psls grep "$1"


    Usage: psls [grep pattern]



    $ psls someApp
    USER PID %CPU %MEM VSZ RSS TT STAT STARTED TIME COMMAND
    root 21 0.0 0.0 2467312 1116 ?? Ss Tue07PM 0:00.17 /sbin/someApp


    Make sure to source your .bashrc (or .bash_profile if you put it there instead):



    source ~/.bashrc


    The function will even auto-complete at the shell command line. As you stated in another answer, you can pipe the first line to a file to save one call to ps.






    share|improve this answer






















    • Nice, I've been using that kind of function for years. I call my version psl, which only call ps and grep once each (and doesn't need head).
      – Adam Katz
      Jan 14 '15 at 21:08


















    up vote
    3
    down vote













    sort but keep header line at the top



    # print the header (the first line of input)
    # and then run the specified command on the body (the rest of the input)
    # use it in a pipeline, e.g. ps | body grep somepattern
    body()
    IFS= read -r header
    printf '%sn' "$header"
    "$@"



    And use it like this



    $ ps aux | body grep someApp
    USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
    1000 11634 51.2 0.1 32824 9112 pts/1 SN+ 13:24 7:49 someApp





    share|improve this answer






















    • Thanks, some of those answers discuss the general case of this question. Perfect!
      – dotancohen
      Sep 13 '12 at 10:07

















    up vote
    2
    down vote













    Another way with gnu ed:



    ed -s '!ps aux' <<< $'2,$v/PATTERN/dn,pnqn'


    or, if the shell supports process substitution:



    printf '%sn' '2,$v/PATTERN/d' ,p q | ed -s <(ps aux)


    that is:



    2,$v/PATTERN/d - remove all lines not matching pattern (ignore the header)
    ,p - print the remaining lines
    q - quit


    More portable, without gnu '!' or shell substitution - using only ed built-in r to read the output of ps aux into the buffer and then delete non-matching lines in the 2,$ range and print the result:



    printf '%sn' 'r !ps aux' '2,$v/PATTERN/d' ,p q | ed -s



    And since the sed commands in the accepted answer output also the line matching themselves, with a sed that supports -f- and a shell that supports process substitution I would run:



    printf '%sn' '2,$' '/PATTERN/!d' '' | sed -f - <(ps aux)


    which pretty much does the same thing as the previous ed commands.






    share|improve this answer





























      up vote
      1
      down vote













      I’m using zsh and this function works well for me:



      function grep1() grep $*)



      The main advantage of this approach is that you have full control over the grep command, so you can pass the usual flags like -i, -E, etc.



      Usage example:



      $ ps -rcA | grep1 databases
      PID TTY TIME CMD

      $ ps -rcA | grep1 -i databases
      PID TTY TIME CMD
      62891 ?? 0:00.33 com.apple.WebKit.Databases





      share|improve this answer



























        up vote
        1
        down vote













        The Perl way:



        ps aux | perl -ne 'print if /pattern/ || $.==1'


        Way easier to read than sed, faster, no risk to pick undesired lines.






        share|improve this answer






















        • Perl?!?
          – dotancohen
          Sep 23 '16 at 8:01

















        up vote
        0
        down vote













        If that's only for grepping processes with full headers, I'd expand @mrb's suggestion:



        $ ps -f -p $(pgrep bash)
        UID PID PPID C STIME TTY STAT TIME CMD
        nasha 2810 2771 0 2014 pts/6 Ss+ 0:00 bash
        ...


        pgrep bash | xargs ps -fp will get the same result but without a subshell. If other formatting is required:



        $ pgrep bash | xargs ps fo uid,pid,stime,cmd -p
        UID PID STIME CMD
        0 3599 2014 -bash
        1000 3286 2014 /bin/bash
        ...





        share|improve this answer





























          up vote
          -1
          down vote













          If you know the exact line numbers, it's easy with perl! If you want to get line 1 and 5 from a file, say /etc/passwd:



          perl -e 'while(<>)if(++$l~~[1,5])print' < /etc/passwd


          If you want to get other lines too, just add their numbers in the array.






          share|improve this answer


















          • 1




            Thank you. As per the OP, I know some of the text in the line, but not the line number.
            – dotancohen
            Mar 23 '16 at 14:46











          • This pops up as an answer on Google when looking for this use case closely related to the OP, so worth noting here.
            – Dagelf
            Mar 23 '16 at 15:19






          • 1




            If that is the case, then I highly suggest that you start a new question and answer it with this answer. It is perfectly fine to answer your own questions on SE, especially in the situation that you mention. Go ahead and link to your new question in a comment on the OP.
            – dotancohen
            Mar 23 '16 at 15:37










          • There are such questions, but they don't currently pop up on Google.
            – Dagelf
            Mar 25 '16 at 13:38










          • Dagelf, bottom line is - your answer doesn't answer the question here. @dotancohen is right - if this pops up as an answer on Google when looking for this use case closely related to the OP then ask a separate question - detailing that closely related use case - and answer it.
            – don_crissti
            Mar 25 '16 at 13:56










          Your Answer







          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "106"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          convertImagesToLinks: false,
          noModals: false,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          bindNavPrevention: true,
          postfix: "",
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













           

          draft saved


          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2funix.stackexchange.com%2fquestions%2f47918%2fhow-to-grep-a-specific-line-and-the-first-line-of-a-file%23new-answer', 'question_page');

          );

          Post as a guest






























          15 Answers
          15






          active

          oldest

          votes








          15 Answers
          15






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes








          up vote
          66
          down vote



          accepted










          Good way



          Normally you can't do this with grep but you can use other tools. AWK was already mentioned but you can also use sed, like this:



          sed -e '1p' -e '/youpattern/!d'


          How it works:



          1. Sed utility works on each line individually, running specified commands on each of them. You can have multiple commands, specifying several -e options. We can prepend each command with a range parameter that specifies if this command should be applied to specific line or not.


          2. "1p" is a first command. It uses p command which normally prints all the lines. But we prepend it with a numerical value that specifies the range it should be applied to. Here, we use 1 which means first line. If you want to print more lines, you can use x,yp where x is first line to print, y is last line to print. For example to print first 3 lines, you would use 1,3p


          3. Next command is d which normally deletes all the lines from buffer. Before this command we put yourpattern between two / characters. This is the other way (first was to specify which lines as we did with p command) of addressing lines that the command should be running at. This means the command will only work for the lines that match yourpattern. Except, we use ! character before d command which inverts its logic. So now it will remove all the lines that do not match specified pattern.


          4. At the end, sed will print all the lines that are left in buffer. But we removed lines that do not match from the buffer so only matching lines will be printed.


          To sum up: we print 1st line, then we delete all the lines that do not match our pattern from input. Rest of the lines are printed (so only lines that do match the pattern).



          First line problem



          As mentioned in comments, there is a problem with this approach. If specified pattern matches also first line, it will be printed twice (once by p command and once because of a match). We can avoid this in two ways:



          1. Adding 1d command after 1p. As I already mentioned, d command deletes lines from buffer and we specify it's range by number 1, which means it will only delete 1st line. So the command would be sed -e '1p' -e '1d' -e '/youpattern/!d'


          2. Using 1b command, instead of 1p. It's a trick. b command allows us to jump to other command specified by a label (this way some commands can be omitted). But if this label is not specified (as in our example) it just jumps to the end of commands, ignoring rest of the commands for our line. So in our case, last d command won't remove this line from buffer.


          Full example:



          ps aux | sed -e '1b' -e '/syslog/!d'


          Using semicolon



          Some sed implementations can save you some typing by using semicolon to separate commands instead of using multiple -e options. So if you don't care about being portable the command would be ps aux | sed '1b;/syslog/!d'. It works at least in GNU sed and busybox implementations.



          Crazy way



          Here's, however, rather crazy way to do this with grep. It's definitely not optimal, I'm posting this just for learning purposes, but you may use it for example, if you don't have any other tool in your system:



          ps aux | grep -n '.*' | grep -e '(^1:)|syslog'


          How it works



          1. First, we use -n option to add line numbers before each line. We want to numerate all the lines we we are matching .* - anything, even empty line. As suggested in comments, we can also match '^', result is the same.


          2. Then we are using extended regular expressions so we can use | special character which works as OR. So we match if the line starts with 1: (first line) or contains our pattern (in this case its syslog).


          Line numbers problem



          Now the problem is, we are getting this ugly line numbers in our output. If this is a problem, we can remove them with cut, like this:



          ps aux | grep -n '.*' | grep -e '(^1:)|syslog' | cut -d ':' -f2-


          -d option specifies delimiter, -f specifies fields (or columns) we want to print. So we want to cut each lines on every : character and print only 2nd and all subsequent columns. This effectively removes first column with it's delimiter and this is exactly what we need.






          share|improve this answer


















          • 4




            Line numbering can be done with cat -n as well and would look clearer as with a grep abused for this.
            – Alfe
            Sep 12 '12 at 13:34







          • 1




            nl does not count empty lines (but prints them without line number), cat -n formats the numbering with preceding spaces, grep -n . strips empty lines at all and adds a colon. All have their ... er ... features ;-)
            – Alfe
            Sep 12 '12 at 15:19






          • 2




            Very educational well-written answer. I tried to replace "Pretend" (Near the beginning) with "Prepend" for you but it wanted more changes and I didn't feel like changing random crap in your post, so you might want to fix that.
            – Bill K
            Sep 12 '12 at 16:57






          • 2




            ps aux | sed '1p;/pattern/!d' will print the first line twice if it matches pattern. Best is to used the b command: ps aux | sed -e 1b -e '/pattern/!d'. cat -n is not POSIX. grep -n '^' would number every line (not an issue for ps output which doesn't have empty lines). nl -ba -d $'n' numbers every line.
            – Stéphane Chazelas
            Sep 13 '12 at 9:46






          • 2




            Note that 1b;... is not portable nor POSIX, there can't be any other command after "b", so you need a newline or another -e expression.
            – Stéphane Chazelas
            Sep 18 '12 at 21:03














          up vote
          66
          down vote



          accepted










          Good way



          Normally you can't do this with grep but you can use other tools. AWK was already mentioned but you can also use sed, like this:



          sed -e '1p' -e '/youpattern/!d'


          How it works:



          1. Sed utility works on each line individually, running specified commands on each of them. You can have multiple commands, specifying several -e options. We can prepend each command with a range parameter that specifies if this command should be applied to specific line or not.


          2. "1p" is a first command. It uses p command which normally prints all the lines. But we prepend it with a numerical value that specifies the range it should be applied to. Here, we use 1 which means first line. If you want to print more lines, you can use x,yp where x is first line to print, y is last line to print. For example to print first 3 lines, you would use 1,3p


          3. Next command is d which normally deletes all the lines from buffer. Before this command we put yourpattern between two / characters. This is the other way (first was to specify which lines as we did with p command) of addressing lines that the command should be running at. This means the command will only work for the lines that match yourpattern. Except, we use ! character before d command which inverts its logic. So now it will remove all the lines that do not match specified pattern.


          4. At the end, sed will print all the lines that are left in buffer. But we removed lines that do not match from the buffer so only matching lines will be printed.


          To sum up: we print 1st line, then we delete all the lines that do not match our pattern from input. Rest of the lines are printed (so only lines that do match the pattern).



          First line problem



          As mentioned in comments, there is a problem with this approach. If specified pattern matches also first line, it will be printed twice (once by p command and once because of a match). We can avoid this in two ways:



          1. Adding 1d command after 1p. As I already mentioned, d command deletes lines from buffer and we specify it's range by number 1, which means it will only delete 1st line. So the command would be sed -e '1p' -e '1d' -e '/youpattern/!d'


          2. Using 1b command, instead of 1p. It's a trick. b command allows us to jump to other command specified by a label (this way some commands can be omitted). But if this label is not specified (as in our example) it just jumps to the end of commands, ignoring rest of the commands for our line. So in our case, last d command won't remove this line from buffer.


          Full example:



          ps aux | sed -e '1b' -e '/syslog/!d'


          Using semicolon



          Some sed implementations can save you some typing by using semicolon to separate commands instead of using multiple -e options. So if you don't care about being portable the command would be ps aux | sed '1b;/syslog/!d'. It works at least in GNU sed and busybox implementations.



          Crazy way



          Here's, however, rather crazy way to do this with grep. It's definitely not optimal, I'm posting this just for learning purposes, but you may use it for example, if you don't have any other tool in your system:



          ps aux | grep -n '.*' | grep -e '(^1:)|syslog'


          How it works



          1. First, we use -n option to add line numbers before each line. We want to numerate all the lines we we are matching .* - anything, even empty line. As suggested in comments, we can also match '^', result is the same.


          2. Then we are using extended regular expressions so we can use | special character which works as OR. So we match if the line starts with 1: (first line) or contains our pattern (in this case its syslog).


          Line numbers problem



          Now the problem is, we are getting this ugly line numbers in our output. If this is a problem, we can remove them with cut, like this:



          ps aux | grep -n '.*' | grep -e '(^1:)|syslog' | cut -d ':' -f2-


          -d option specifies delimiter, -f specifies fields (or columns) we want to print. So we want to cut each lines on every : character and print only 2nd and all subsequent columns. This effectively removes first column with it's delimiter and this is exactly what we need.






          share|improve this answer


















          • 4




            Line numbering can be done with cat -n as well and would look clearer as with a grep abused for this.
            – Alfe
            Sep 12 '12 at 13:34







          • 1




            nl does not count empty lines (but prints them without line number), cat -n formats the numbering with preceding spaces, grep -n . strips empty lines at all and adds a colon. All have their ... er ... features ;-)
            – Alfe
            Sep 12 '12 at 15:19






          • 2




            Very educational well-written answer. I tried to replace "Pretend" (Near the beginning) with "Prepend" for you but it wanted more changes and I didn't feel like changing random crap in your post, so you might want to fix that.
            – Bill K
            Sep 12 '12 at 16:57






          • 2




            ps aux | sed '1p;/pattern/!d' will print the first line twice if it matches pattern. Best is to used the b command: ps aux | sed -e 1b -e '/pattern/!d'. cat -n is not POSIX. grep -n '^' would number every line (not an issue for ps output which doesn't have empty lines). nl -ba -d $'n' numbers every line.
            – Stéphane Chazelas
            Sep 13 '12 at 9:46






          • 2




            Note that 1b;... is not portable nor POSIX, there can't be any other command after "b", so you need a newline or another -e expression.
            – Stéphane Chazelas
            Sep 18 '12 at 21:03












          up vote
          66
          down vote



          accepted







          up vote
          66
          down vote



          accepted






          Good way



          Normally you can't do this with grep but you can use other tools. AWK was already mentioned but you can also use sed, like this:



          sed -e '1p' -e '/youpattern/!d'


          How it works:



          1. Sed utility works on each line individually, running specified commands on each of them. You can have multiple commands, specifying several -e options. We can prepend each command with a range parameter that specifies if this command should be applied to specific line or not.


          2. "1p" is a first command. It uses p command which normally prints all the lines. But we prepend it with a numerical value that specifies the range it should be applied to. Here, we use 1 which means first line. If you want to print more lines, you can use x,yp where x is first line to print, y is last line to print. For example to print first 3 lines, you would use 1,3p


          3. Next command is d which normally deletes all the lines from buffer. Before this command we put yourpattern between two / characters. This is the other way (first was to specify which lines as we did with p command) of addressing lines that the command should be running at. This means the command will only work for the lines that match yourpattern. Except, we use ! character before d command which inverts its logic. So now it will remove all the lines that do not match specified pattern.


          4. At the end, sed will print all the lines that are left in buffer. But we removed lines that do not match from the buffer so only matching lines will be printed.


          To sum up: we print 1st line, then we delete all the lines that do not match our pattern from input. Rest of the lines are printed (so only lines that do match the pattern).



          First line problem



          As mentioned in comments, there is a problem with this approach. If specified pattern matches also first line, it will be printed twice (once by p command and once because of a match). We can avoid this in two ways:



          1. Adding 1d command after 1p. As I already mentioned, d command deletes lines from buffer and we specify it's range by number 1, which means it will only delete 1st line. So the command would be sed -e '1p' -e '1d' -e '/youpattern/!d'


          2. Using 1b command, instead of 1p. It's a trick. b command allows us to jump to other command specified by a label (this way some commands can be omitted). But if this label is not specified (as in our example) it just jumps to the end of commands, ignoring rest of the commands for our line. So in our case, last d command won't remove this line from buffer.


          Full example:



          ps aux | sed -e '1b' -e '/syslog/!d'


          Using semicolon



          Some sed implementations can save you some typing by using semicolon to separate commands instead of using multiple -e options. So if you don't care about being portable the command would be ps aux | sed '1b;/syslog/!d'. It works at least in GNU sed and busybox implementations.



          Crazy way



          Here's, however, rather crazy way to do this with grep. It's definitely not optimal, I'm posting this just for learning purposes, but you may use it for example, if you don't have any other tool in your system:



          ps aux | grep -n '.*' | grep -e '(^1:)|syslog'


          How it works



          1. First, we use -n option to add line numbers before each line. We want to numerate all the lines we we are matching .* - anything, even empty line. As suggested in comments, we can also match '^', result is the same.


          2. Then we are using extended regular expressions so we can use | special character which works as OR. So we match if the line starts with 1: (first line) or contains our pattern (in this case its syslog).


          Line numbers problem



          Now the problem is, we are getting this ugly line numbers in our output. If this is a problem, we can remove them with cut, like this:



          ps aux | grep -n '.*' | grep -e '(^1:)|syslog' | cut -d ':' -f2-


          -d option specifies delimiter, -f specifies fields (or columns) we want to print. So we want to cut each lines on every : character and print only 2nd and all subsequent columns. This effectively removes first column with it's delimiter and this is exactly what we need.






          share|improve this answer














          Good way



          Normally you can't do this with grep but you can use other tools. AWK was already mentioned but you can also use sed, like this:



          sed -e '1p' -e '/youpattern/!d'


          How it works:



          1. Sed utility works on each line individually, running specified commands on each of them. You can have multiple commands, specifying several -e options. We can prepend each command with a range parameter that specifies if this command should be applied to specific line or not.


          2. "1p" is a first command. It uses p command which normally prints all the lines. But we prepend it with a numerical value that specifies the range it should be applied to. Here, we use 1 which means first line. If you want to print more lines, you can use x,yp where x is first line to print, y is last line to print. For example to print first 3 lines, you would use 1,3p


          3. Next command is d which normally deletes all the lines from buffer. Before this command we put yourpattern between two / characters. This is the other way (first was to specify which lines as we did with p command) of addressing lines that the command should be running at. This means the command will only work for the lines that match yourpattern. Except, we use ! character before d command which inverts its logic. So now it will remove all the lines that do not match specified pattern.


          4. At the end, sed will print all the lines that are left in buffer. But we removed lines that do not match from the buffer so only matching lines will be printed.


          To sum up: we print 1st line, then we delete all the lines that do not match our pattern from input. Rest of the lines are printed (so only lines that do match the pattern).



          First line problem



          As mentioned in comments, there is a problem with this approach. If specified pattern matches also first line, it will be printed twice (once by p command and once because of a match). We can avoid this in two ways:



          1. Adding 1d command after 1p. As I already mentioned, d command deletes lines from buffer and we specify it's range by number 1, which means it will only delete 1st line. So the command would be sed -e '1p' -e '1d' -e '/youpattern/!d'


          2. Using 1b command, instead of 1p. It's a trick. b command allows us to jump to other command specified by a label (this way some commands can be omitted). But if this label is not specified (as in our example) it just jumps to the end of commands, ignoring rest of the commands for our line. So in our case, last d command won't remove this line from buffer.


          Full example:



          ps aux | sed -e '1b' -e '/syslog/!d'


          Using semicolon



          Some sed implementations can save you some typing by using semicolon to separate commands instead of using multiple -e options. So if you don't care about being portable the command would be ps aux | sed '1b;/syslog/!d'. It works at least in GNU sed and busybox implementations.



          Crazy way



          Here's, however, rather crazy way to do this with grep. It's definitely not optimal, I'm posting this just for learning purposes, but you may use it for example, if you don't have any other tool in your system:



          ps aux | grep -n '.*' | grep -e '(^1:)|syslog'


          How it works



          1. First, we use -n option to add line numbers before each line. We want to numerate all the lines we we are matching .* - anything, even empty line. As suggested in comments, we can also match '^', result is the same.


          2. Then we are using extended regular expressions so we can use | special character which works as OR. So we match if the line starts with 1: (first line) or contains our pattern (in this case its syslog).


          Line numbers problem



          Now the problem is, we are getting this ugly line numbers in our output. If this is a problem, we can remove them with cut, like this:



          ps aux | grep -n '.*' | grep -e '(^1:)|syslog' | cut -d ':' -f2-


          -d option specifies delimiter, -f specifies fields (or columns) we want to print. So we want to cut each lines on every : character and print only 2nd and all subsequent columns. This effectively removes first column with it's delimiter and this is exactly what we need.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Jan 12 '15 at 18:58

























          answered Sep 12 '12 at 11:24









          Krzysztof Adamski

          3,1081619




          3,1081619







          • 4




            Line numbering can be done with cat -n as well and would look clearer as with a grep abused for this.
            – Alfe
            Sep 12 '12 at 13:34







          • 1




            nl does not count empty lines (but prints them without line number), cat -n formats the numbering with preceding spaces, grep -n . strips empty lines at all and adds a colon. All have their ... er ... features ;-)
            – Alfe
            Sep 12 '12 at 15:19






          • 2




            Very educational well-written answer. I tried to replace "Pretend" (Near the beginning) with "Prepend" for you but it wanted more changes and I didn't feel like changing random crap in your post, so you might want to fix that.
            – Bill K
            Sep 12 '12 at 16:57






          • 2




            ps aux | sed '1p;/pattern/!d' will print the first line twice if it matches pattern. Best is to used the b command: ps aux | sed -e 1b -e '/pattern/!d'. cat -n is not POSIX. grep -n '^' would number every line (not an issue for ps output which doesn't have empty lines). nl -ba -d $'n' numbers every line.
            – Stéphane Chazelas
            Sep 13 '12 at 9:46






          • 2




            Note that 1b;... is not portable nor POSIX, there can't be any other command after "b", so you need a newline or another -e expression.
            – Stéphane Chazelas
            Sep 18 '12 at 21:03












          • 4




            Line numbering can be done with cat -n as well and would look clearer as with a grep abused for this.
            – Alfe
            Sep 12 '12 at 13:34







          • 1




            nl does not count empty lines (but prints them without line number), cat -n formats the numbering with preceding spaces, grep -n . strips empty lines at all and adds a colon. All have their ... er ... features ;-)
            – Alfe
            Sep 12 '12 at 15:19






          • 2




            Very educational well-written answer. I tried to replace "Pretend" (Near the beginning) with "Prepend" for you but it wanted more changes and I didn't feel like changing random crap in your post, so you might want to fix that.
            – Bill K
            Sep 12 '12 at 16:57






          • 2




            ps aux | sed '1p;/pattern/!d' will print the first line twice if it matches pattern. Best is to used the b command: ps aux | sed -e 1b -e '/pattern/!d'. cat -n is not POSIX. grep -n '^' would number every line (not an issue for ps output which doesn't have empty lines). nl -ba -d $'n' numbers every line.
            – Stéphane Chazelas
            Sep 13 '12 at 9:46






          • 2




            Note that 1b;... is not portable nor POSIX, there can't be any other command after "b", so you need a newline or another -e expression.
            – Stéphane Chazelas
            Sep 18 '12 at 21:03







          4




          4




          Line numbering can be done with cat -n as well and would look clearer as with a grep abused for this.
          – Alfe
          Sep 12 '12 at 13:34





          Line numbering can be done with cat -n as well and would look clearer as with a grep abused for this.
          – Alfe
          Sep 12 '12 at 13:34





          1




          1




          nl does not count empty lines (but prints them without line number), cat -n formats the numbering with preceding spaces, grep -n . strips empty lines at all and adds a colon. All have their ... er ... features ;-)
          – Alfe
          Sep 12 '12 at 15:19




          nl does not count empty lines (but prints them without line number), cat -n formats the numbering with preceding spaces, grep -n . strips empty lines at all and adds a colon. All have their ... er ... features ;-)
          – Alfe
          Sep 12 '12 at 15:19




          2




          2




          Very educational well-written answer. I tried to replace "Pretend" (Near the beginning) with "Prepend" for you but it wanted more changes and I didn't feel like changing random crap in your post, so you might want to fix that.
          – Bill K
          Sep 12 '12 at 16:57




          Very educational well-written answer. I tried to replace "Pretend" (Near the beginning) with "Prepend" for you but it wanted more changes and I didn't feel like changing random crap in your post, so you might want to fix that.
          – Bill K
          Sep 12 '12 at 16:57




          2




          2




          ps aux | sed '1p;/pattern/!d' will print the first line twice if it matches pattern. Best is to used the b command: ps aux | sed -e 1b -e '/pattern/!d'. cat -n is not POSIX. grep -n '^' would number every line (not an issue for ps output which doesn't have empty lines). nl -ba -d $'n' numbers every line.
          – Stéphane Chazelas
          Sep 13 '12 at 9:46




          ps aux | sed '1p;/pattern/!d' will print the first line twice if it matches pattern. Best is to used the b command: ps aux | sed -e 1b -e '/pattern/!d'. cat -n is not POSIX. grep -n '^' would number every line (not an issue for ps output which doesn't have empty lines). nl -ba -d $'n' numbers every line.
          – Stéphane Chazelas
          Sep 13 '12 at 9:46




          2




          2




          Note that 1b;... is not portable nor POSIX, there can't be any other command after "b", so you need a newline or another -e expression.
          – Stéphane Chazelas
          Sep 18 '12 at 21:03




          Note that 1b;... is not portable nor POSIX, there can't be any other command after "b", so you need a newline or another -e expression.
          – Stéphane Chazelas
          Sep 18 '12 at 21:03












          up vote
          57
          down vote













          How do you feel about using awk instead of grep?



          chopper:~> ps aux | awk 'NR == 1 || /syslogd/'
          USER PID %CPU %MEM VSZ RSS TT STAT STARTED TIME COMMAND
          root 19 0.0 0.0 2518684 1160 ?? Ss 26Aug12 1:00.22 /usr/sbin/syslogd
          mrb 574 0.0 0.0 2432852 696 s006 R+ 8:04am 0:00.00 awk NR == 1 || /syslogd/



          • NR == 1: Number of record == 1; ie. the first line


          • ||: or:


          • /syslogd/: Pattern to search for

          It might also be worth looking at pgrep, although this is more for scripts rather than user-facing output. It does avoid the grep command itself from appearing in the output, though.



          chopper:~> pgrep -l syslogd
          19 syslogd





          share|improve this answer




















          • Very nice, thanks. This is also nicely scriptable for future expansion.
            – dotancohen
            Sep 12 '12 at 14:30










          • I need to learn me some awk. very nice.
            – user606723
            Sep 13 '12 at 15:43














          up vote
          57
          down vote













          How do you feel about using awk instead of grep?



          chopper:~> ps aux | awk 'NR == 1 || /syslogd/'
          USER PID %CPU %MEM VSZ RSS TT STAT STARTED TIME COMMAND
          root 19 0.0 0.0 2518684 1160 ?? Ss 26Aug12 1:00.22 /usr/sbin/syslogd
          mrb 574 0.0 0.0 2432852 696 s006 R+ 8:04am 0:00.00 awk NR == 1 || /syslogd/



          • NR == 1: Number of record == 1; ie. the first line


          • ||: or:


          • /syslogd/: Pattern to search for

          It might also be worth looking at pgrep, although this is more for scripts rather than user-facing output. It does avoid the grep command itself from appearing in the output, though.



          chopper:~> pgrep -l syslogd
          19 syslogd





          share|improve this answer




















          • Very nice, thanks. This is also nicely scriptable for future expansion.
            – dotancohen
            Sep 12 '12 at 14:30










          • I need to learn me some awk. very nice.
            – user606723
            Sep 13 '12 at 15:43












          up vote
          57
          down vote










          up vote
          57
          down vote









          How do you feel about using awk instead of grep?



          chopper:~> ps aux | awk 'NR == 1 || /syslogd/'
          USER PID %CPU %MEM VSZ RSS TT STAT STARTED TIME COMMAND
          root 19 0.0 0.0 2518684 1160 ?? Ss 26Aug12 1:00.22 /usr/sbin/syslogd
          mrb 574 0.0 0.0 2432852 696 s006 R+ 8:04am 0:00.00 awk NR == 1 || /syslogd/



          • NR == 1: Number of record == 1; ie. the first line


          • ||: or:


          • /syslogd/: Pattern to search for

          It might also be worth looking at pgrep, although this is more for scripts rather than user-facing output. It does avoid the grep command itself from appearing in the output, though.



          chopper:~> pgrep -l syslogd
          19 syslogd





          share|improve this answer












          How do you feel about using awk instead of grep?



          chopper:~> ps aux | awk 'NR == 1 || /syslogd/'
          USER PID %CPU %MEM VSZ RSS TT STAT STARTED TIME COMMAND
          root 19 0.0 0.0 2518684 1160 ?? Ss 26Aug12 1:00.22 /usr/sbin/syslogd
          mrb 574 0.0 0.0 2432852 696 s006 R+ 8:04am 0:00.00 awk NR == 1 || /syslogd/



          • NR == 1: Number of record == 1; ie. the first line


          • ||: or:


          • /syslogd/: Pattern to search for

          It might also be worth looking at pgrep, although this is more for scripts rather than user-facing output. It does avoid the grep command itself from appearing in the output, though.



          chopper:~> pgrep -l syslogd
          19 syslogd






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Sep 12 '12 at 11:08









          mrb

          7,24912432




          7,24912432











          • Very nice, thanks. This is also nicely scriptable for future expansion.
            – dotancohen
            Sep 12 '12 at 14:30










          • I need to learn me some awk. very nice.
            – user606723
            Sep 13 '12 at 15:43
















          • Very nice, thanks. This is also nicely scriptable for future expansion.
            – dotancohen
            Sep 12 '12 at 14:30










          • I need to learn me some awk. very nice.
            – user606723
            Sep 13 '12 at 15:43















          Very nice, thanks. This is also nicely scriptable for future expansion.
          – dotancohen
          Sep 12 '12 at 14:30




          Very nice, thanks. This is also nicely scriptable for future expansion.
          – dotancohen
          Sep 12 '12 at 14:30












          I need to learn me some awk. very nice.
          – user606723
          Sep 13 '12 at 15:43




          I need to learn me some awk. very nice.
          – user606723
          Sep 13 '12 at 15:43










          up vote
          29
          down vote













          ps aux | read line;echo "$line";grep someApp;


          EDIT: after comments



          ps aux | head -1;grep someApp;


          I though head -1 would read all input, but after testing it, it works too.



           head -1;grep ok; <<END
          this is a test
          this line should be ok
          not this one
          END


          output is



          this is a test
          this line should be ok





          share|improve this answer


















          • 2




            That's the idea spelled out directly in bash. I'd like to give more than one thumbs-up for this. I'd just maybe use IFS='' read line; ... in case the header starts with spaces.
            – Alfe
            Sep 12 '12 at 13:31











          • This does exactly attack the problem directly. Nice!
            – dotancohen
            Sep 12 '12 at 14:36







          • 3




            I'd just use head -1 instead of the read/echo combo.
            – chepner
            Sep 12 '12 at 16:07






          • 1




            Well, it works with head -n1 on my bash. This can probably be implementation specific. My head is not reading whole input in this case, only first line, leaving rest of them in the input buffer.
            – Krzysztof Adamski
            Sep 13 '12 at 10:11






          • 2




            head -n1 is shorter, but it appears even the POSIX spec is silent as to how much of its input it is allowed to read, so perhaps read line; echo $line is more portable after all.
            – chepner
            Sep 13 '12 at 11:59














          up vote
          29
          down vote













          ps aux | read line;echo "$line";grep someApp;


          EDIT: after comments



          ps aux | head -1;grep someApp;


          I though head -1 would read all input, but after testing it, it works too.



           head -1;grep ok; <<END
          this is a test
          this line should be ok
          not this one
          END


          output is



          this is a test
          this line should be ok





          share|improve this answer


















          • 2




            That's the idea spelled out directly in bash. I'd like to give more than one thumbs-up for this. I'd just maybe use IFS='' read line; ... in case the header starts with spaces.
            – Alfe
            Sep 12 '12 at 13:31











          • This does exactly attack the problem directly. Nice!
            – dotancohen
            Sep 12 '12 at 14:36







          • 3




            I'd just use head -1 instead of the read/echo combo.
            – chepner
            Sep 12 '12 at 16:07






          • 1




            Well, it works with head -n1 on my bash. This can probably be implementation specific. My head is not reading whole input in this case, only first line, leaving rest of them in the input buffer.
            – Krzysztof Adamski
            Sep 13 '12 at 10:11






          • 2




            head -n1 is shorter, but it appears even the POSIX spec is silent as to how much of its input it is allowed to read, so perhaps read line; echo $line is more portable after all.
            – chepner
            Sep 13 '12 at 11:59












          up vote
          29
          down vote










          up vote
          29
          down vote









          ps aux | read line;echo "$line";grep someApp;


          EDIT: after comments



          ps aux | head -1;grep someApp;


          I though head -1 would read all input, but after testing it, it works too.



           head -1;grep ok; <<END
          this is a test
          this line should be ok
          not this one
          END


          output is



          this is a test
          this line should be ok





          share|improve this answer














          ps aux | read line;echo "$line";grep someApp;


          EDIT: after comments



          ps aux | head -1;grep someApp;


          I though head -1 would read all input, but after testing it, it works too.



           head -1;grep ok; <<END
          this is a test
          this line should be ok
          not this one
          END


          output is



          this is a test
          this line should be ok






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Sep 13 '12 at 11:47

























          answered Sep 12 '12 at 12:46









          Nahuel Fouilleul

          1,08667




          1,08667







          • 2




            That's the idea spelled out directly in bash. I'd like to give more than one thumbs-up for this. I'd just maybe use IFS='' read line; ... in case the header starts with spaces.
            – Alfe
            Sep 12 '12 at 13:31











          • This does exactly attack the problem directly. Nice!
            – dotancohen
            Sep 12 '12 at 14:36







          • 3




            I'd just use head -1 instead of the read/echo combo.
            – chepner
            Sep 12 '12 at 16:07






          • 1




            Well, it works with head -n1 on my bash. This can probably be implementation specific. My head is not reading whole input in this case, only first line, leaving rest of them in the input buffer.
            – Krzysztof Adamski
            Sep 13 '12 at 10:11






          • 2




            head -n1 is shorter, but it appears even the POSIX spec is silent as to how much of its input it is allowed to read, so perhaps read line; echo $line is more portable after all.
            – chepner
            Sep 13 '12 at 11:59












          • 2




            That's the idea spelled out directly in bash. I'd like to give more than one thumbs-up for this. I'd just maybe use IFS='' read line; ... in case the header starts with spaces.
            – Alfe
            Sep 12 '12 at 13:31











          • This does exactly attack the problem directly. Nice!
            – dotancohen
            Sep 12 '12 at 14:36







          • 3




            I'd just use head -1 instead of the read/echo combo.
            – chepner
            Sep 12 '12 at 16:07






          • 1




            Well, it works with head -n1 on my bash. This can probably be implementation specific. My head is not reading whole input in this case, only first line, leaving rest of them in the input buffer.
            – Krzysztof Adamski
            Sep 13 '12 at 10:11






          • 2




            head -n1 is shorter, but it appears even the POSIX spec is silent as to how much of its input it is allowed to read, so perhaps read line; echo $line is more portable after all.
            – chepner
            Sep 13 '12 at 11:59







          2




          2




          That's the idea spelled out directly in bash. I'd like to give more than one thumbs-up for this. I'd just maybe use IFS='' read line; ... in case the header starts with spaces.
          – Alfe
          Sep 12 '12 at 13:31





          That's the idea spelled out directly in bash. I'd like to give more than one thumbs-up for this. I'd just maybe use IFS='' read line; ... in case the header starts with spaces.
          – Alfe
          Sep 12 '12 at 13:31













          This does exactly attack the problem directly. Nice!
          – dotancohen
          Sep 12 '12 at 14:36





          This does exactly attack the problem directly. Nice!
          – dotancohen
          Sep 12 '12 at 14:36





          3




          3




          I'd just use head -1 instead of the read/echo combo.
          – chepner
          Sep 12 '12 at 16:07




          I'd just use head -1 instead of the read/echo combo.
          – chepner
          Sep 12 '12 at 16:07




          1




          1




          Well, it works with head -n1 on my bash. This can probably be implementation specific. My head is not reading whole input in this case, only first line, leaving rest of them in the input buffer.
          – Krzysztof Adamski
          Sep 13 '12 at 10:11




          Well, it works with head -n1 on my bash. This can probably be implementation specific. My head is not reading whole input in this case, only first line, leaving rest of them in the input buffer.
          – Krzysztof Adamski
          Sep 13 '12 at 10:11




          2




          2




          head -n1 is shorter, but it appears even the POSIX spec is silent as to how much of its input it is allowed to read, so perhaps read line; echo $line is more portable after all.
          – chepner
          Sep 13 '12 at 11:59




          head -n1 is shorter, but it appears even the POSIX spec is silent as to how much of its input it is allowed to read, so perhaps read line; echo $line is more portable after all.
          – chepner
          Sep 13 '12 at 11:59










          up vote
          14
          down vote













          Ps support internal filter,



          Suppose you're looking for bash process:



          ps -C bash -f



          Will list all process that named bash.






          share|improve this answer




















          • Thanks, that is nice to know. However, it won't find scripts started from python, among others.
            – dotancohen
            Sep 12 '12 at 14:32














          up vote
          14
          down vote













          Ps support internal filter,



          Suppose you're looking for bash process:



          ps -C bash -f



          Will list all process that named bash.






          share|improve this answer




















          • Thanks, that is nice to know. However, it won't find scripts started from python, among others.
            – dotancohen
            Sep 12 '12 at 14:32












          up vote
          14
          down vote










          up vote
          14
          down vote









          Ps support internal filter,



          Suppose you're looking for bash process:



          ps -C bash -f



          Will list all process that named bash.






          share|improve this answer












          Ps support internal filter,



          Suppose you're looking for bash process:



          ps -C bash -f



          Will list all process that named bash.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Sep 12 '12 at 11:14









          daisy

          27.8k46161293




          27.8k46161293











          • Thanks, that is nice to know. However, it won't find scripts started from python, among others.
            – dotancohen
            Sep 12 '12 at 14:32
















          • Thanks, that is nice to know. However, it won't find scripts started from python, among others.
            – dotancohen
            Sep 12 '12 at 14:32















          Thanks, that is nice to know. However, it won't find scripts started from python, among others.
          – dotancohen
          Sep 12 '12 at 14:32




          Thanks, that is nice to know. However, it won't find scripts started from python, among others.
          – dotancohen
          Sep 12 '12 at 14:32










          up vote
          5
          down vote













          I tend to send the header to stderr:



          ps | (IFS= read -r HEADER; echo "$HEADER" >&2; cat) | grep ps


          This is usually sufficient for human reading purposes. e.g.:



           PID TTY TIME CMD
          4738 pts/0 00:00:00 ps


          The bracketed part could go into its own script for general use.



          There's an added convenience in that the output can be further piped (to sort etc.) and the header will remain on top.






          share|improve this answer
























            up vote
            5
            down vote













            I tend to send the header to stderr:



            ps | (IFS= read -r HEADER; echo "$HEADER" >&2; cat) | grep ps


            This is usually sufficient for human reading purposes. e.g.:



             PID TTY TIME CMD
            4738 pts/0 00:00:00 ps


            The bracketed part could go into its own script for general use.



            There's an added convenience in that the output can be further piped (to sort etc.) and the header will remain on top.






            share|improve this answer






















              up vote
              5
              down vote










              up vote
              5
              down vote









              I tend to send the header to stderr:



              ps | (IFS= read -r HEADER; echo "$HEADER" >&2; cat) | grep ps


              This is usually sufficient for human reading purposes. e.g.:



               PID TTY TIME CMD
              4738 pts/0 00:00:00 ps


              The bracketed part could go into its own script for general use.



              There's an added convenience in that the output can be further piped (to sort etc.) and the header will remain on top.






              share|improve this answer












              I tend to send the header to stderr:



              ps | (IFS= read -r HEADER; echo "$HEADER" >&2; cat) | grep ps


              This is usually sufficient for human reading purposes. e.g.:



               PID TTY TIME CMD
              4738 pts/0 00:00:00 ps


              The bracketed part could go into its own script for general use.



              There's an added convenience in that the output can be further piped (to sort etc.) and the header will remain on top.







              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered Sep 13 '12 at 5:21









              antak

              49058




              49058




















                  up vote
                  5
                  down vote













                  You could also use tee and head:



                  ps aux | tee >(head -n1) | grep syslog


                  Note however that as long as tee is unable to ignore SIGPIPE signals (see e.g. the discussion here) this approach needs a workaround to be reliable. The workaround is to ignore SIGPIPE signals, this can for example be done like this in bash like shells:



                  trap '' PIPE # ignore SIGPIPE
                  ps aux | tee >(head -n1) 2> /dev/null | grep syslog
                  trap - PIPE # restore SIGPIPE handling


                  Also note that the output order is not guaranteed.






                  share|improve this answer






















                  • I would not rely on this to work, the first time I ran it (zsh) it produced column headers below grep results. Second time it was fine.
                    – Rqomey
                    Sep 12 '12 at 12:16






                  • 1




                    I haven't seen this yet, but one way to increase reliability is to insert a small delay in the pipeline before the grep: | sleep .5; cat .
                    – Thor
                    Sep 12 '12 at 12:42






                  • 2




                    Adding sleeps to avoid concurrency problems is always a hack. Though this might work, it's a step towards the dark side. -1 for this.
                    – Alfe
                    Sep 12 '12 at 13:36






                  • 1




                    I have had a few other strange issues while trying this answer, I set up a question to check
                    – Rqomey
                    Sep 12 '12 at 13:47











                  • This is an interesting use of tee, but I find it unreliable and often only prints the output line, but not the header line.
                    – dotancohen
                    Sep 12 '12 at 14:32














                  up vote
                  5
                  down vote













                  You could also use tee and head:



                  ps aux | tee >(head -n1) | grep syslog


                  Note however that as long as tee is unable to ignore SIGPIPE signals (see e.g. the discussion here) this approach needs a workaround to be reliable. The workaround is to ignore SIGPIPE signals, this can for example be done like this in bash like shells:



                  trap '' PIPE # ignore SIGPIPE
                  ps aux | tee >(head -n1) 2> /dev/null | grep syslog
                  trap - PIPE # restore SIGPIPE handling


                  Also note that the output order is not guaranteed.






                  share|improve this answer






















                  • I would not rely on this to work, the first time I ran it (zsh) it produced column headers below grep results. Second time it was fine.
                    – Rqomey
                    Sep 12 '12 at 12:16






                  • 1




                    I haven't seen this yet, but one way to increase reliability is to insert a small delay in the pipeline before the grep: | sleep .5; cat .
                    – Thor
                    Sep 12 '12 at 12:42






                  • 2




                    Adding sleeps to avoid concurrency problems is always a hack. Though this might work, it's a step towards the dark side. -1 for this.
                    – Alfe
                    Sep 12 '12 at 13:36






                  • 1




                    I have had a few other strange issues while trying this answer, I set up a question to check
                    – Rqomey
                    Sep 12 '12 at 13:47











                  • This is an interesting use of tee, but I find it unreliable and often only prints the output line, but not the header line.
                    – dotancohen
                    Sep 12 '12 at 14:32












                  up vote
                  5
                  down vote










                  up vote
                  5
                  down vote









                  You could also use tee and head:



                  ps aux | tee >(head -n1) | grep syslog


                  Note however that as long as tee is unable to ignore SIGPIPE signals (see e.g. the discussion here) this approach needs a workaround to be reliable. The workaround is to ignore SIGPIPE signals, this can for example be done like this in bash like shells:



                  trap '' PIPE # ignore SIGPIPE
                  ps aux | tee >(head -n1) 2> /dev/null | grep syslog
                  trap - PIPE # restore SIGPIPE handling


                  Also note that the output order is not guaranteed.






                  share|improve this answer














                  You could also use tee and head:



                  ps aux | tee >(head -n1) | grep syslog


                  Note however that as long as tee is unable to ignore SIGPIPE signals (see e.g. the discussion here) this approach needs a workaround to be reliable. The workaround is to ignore SIGPIPE signals, this can for example be done like this in bash like shells:



                  trap '' PIPE # ignore SIGPIPE
                  ps aux | tee >(head -n1) 2> /dev/null | grep syslog
                  trap - PIPE # restore SIGPIPE handling


                  Also note that the output order is not guaranteed.







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Apr 13 '17 at 12:36









                  Community♦

                  1




                  1










                  answered Sep 12 '12 at 11:19









                  Thor

                  11.2k13256




                  11.2k13256











                  • I would not rely on this to work, the first time I ran it (zsh) it produced column headers below grep results. Second time it was fine.
                    – Rqomey
                    Sep 12 '12 at 12:16






                  • 1




                    I haven't seen this yet, but one way to increase reliability is to insert a small delay in the pipeline before the grep: | sleep .5; cat .
                    – Thor
                    Sep 12 '12 at 12:42






                  • 2




                    Adding sleeps to avoid concurrency problems is always a hack. Though this might work, it's a step towards the dark side. -1 for this.
                    – Alfe
                    Sep 12 '12 at 13:36






                  • 1




                    I have had a few other strange issues while trying this answer, I set up a question to check
                    – Rqomey
                    Sep 12 '12 at 13:47











                  • This is an interesting use of tee, but I find it unreliable and often only prints the output line, but not the header line.
                    – dotancohen
                    Sep 12 '12 at 14:32
















                  • I would not rely on this to work, the first time I ran it (zsh) it produced column headers below grep results. Second time it was fine.
                    – Rqomey
                    Sep 12 '12 at 12:16






                  • 1




                    I haven't seen this yet, but one way to increase reliability is to insert a small delay in the pipeline before the grep: | sleep .5; cat .
                    – Thor
                    Sep 12 '12 at 12:42






                  • 2




                    Adding sleeps to avoid concurrency problems is always a hack. Though this might work, it's a step towards the dark side. -1 for this.
                    – Alfe
                    Sep 12 '12 at 13:36






                  • 1




                    I have had a few other strange issues while trying this answer, I set up a question to check
                    – Rqomey
                    Sep 12 '12 at 13:47











                  • This is an interesting use of tee, but I find it unreliable and often only prints the output line, but not the header line.
                    – dotancohen
                    Sep 12 '12 at 14:32















                  I would not rely on this to work, the first time I ran it (zsh) it produced column headers below grep results. Second time it was fine.
                  – Rqomey
                  Sep 12 '12 at 12:16




                  I would not rely on this to work, the first time I ran it (zsh) it produced column headers below grep results. Second time it was fine.
                  – Rqomey
                  Sep 12 '12 at 12:16




                  1




                  1




                  I haven't seen this yet, but one way to increase reliability is to insert a small delay in the pipeline before the grep: | sleep .5; cat .
                  – Thor
                  Sep 12 '12 at 12:42




                  I haven't seen this yet, but one way to increase reliability is to insert a small delay in the pipeline before the grep: | sleep .5; cat .
                  – Thor
                  Sep 12 '12 at 12:42




                  2




                  2




                  Adding sleeps to avoid concurrency problems is always a hack. Though this might work, it's a step towards the dark side. -1 for this.
                  – Alfe
                  Sep 12 '12 at 13:36




                  Adding sleeps to avoid concurrency problems is always a hack. Though this might work, it's a step towards the dark side. -1 for this.
                  – Alfe
                  Sep 12 '12 at 13:36




                  1




                  1




                  I have had a few other strange issues while trying this answer, I set up a question to check
                  – Rqomey
                  Sep 12 '12 at 13:47





                  I have had a few other strange issues while trying this answer, I set up a question to check
                  – Rqomey
                  Sep 12 '12 at 13:47













                  This is an interesting use of tee, but I find it unreliable and often only prints the output line, but not the header line.
                  – dotancohen
                  Sep 12 '12 at 14:32




                  This is an interesting use of tee, but I find it unreliable and often only prints the output line, but not the header line.
                  – dotancohen
                  Sep 12 '12 at 14:32










                  up vote
                  4
                  down vote













                  Perhaps two ps commands would be easiest.



                  $ ps aux | head -1 && ps aux | grep someApp
                  USER PID %CPU %MEM VSZ RSS TT STAT STARTED TIME COMMAND
                  100 3304 0.0 0.2 2466308 6476 ?? Ss 2Sep12 0:01.75 /usr/bin/someApp





                  share|improve this answer
















                  • 2




                    I don't like this solution, primarily because the situation could change between the first and second ps aux call... And if you just want that static first line, why not echo it manually?
                    – Shadur
                    Sep 12 '12 at 11:19






                  • 1




                    Changes between the two calls aren't to be bothered in this situation. The first will only provide the headline which will always fit to the output of the second.
                    – Alfe
                    Sep 12 '12 at 13:30







                  • 2




                    I don't see why this was downvoted, it certainly is a viable option. Upvoting.
                    – dotancohen
                    Sep 12 '12 at 14:37














                  up vote
                  4
                  down vote













                  Perhaps two ps commands would be easiest.



                  $ ps aux | head -1 && ps aux | grep someApp
                  USER PID %CPU %MEM VSZ RSS TT STAT STARTED TIME COMMAND
                  100 3304 0.0 0.2 2466308 6476 ?? Ss 2Sep12 0:01.75 /usr/bin/someApp





                  share|improve this answer
















                  • 2




                    I don't like this solution, primarily because the situation could change between the first and second ps aux call... And if you just want that static first line, why not echo it manually?
                    – Shadur
                    Sep 12 '12 at 11:19






                  • 1




                    Changes between the two calls aren't to be bothered in this situation. The first will only provide the headline which will always fit to the output of the second.
                    – Alfe
                    Sep 12 '12 at 13:30







                  • 2




                    I don't see why this was downvoted, it certainly is a viable option. Upvoting.
                    – dotancohen
                    Sep 12 '12 at 14:37












                  up vote
                  4
                  down vote










                  up vote
                  4
                  down vote









                  Perhaps two ps commands would be easiest.



                  $ ps aux | head -1 && ps aux | grep someApp
                  USER PID %CPU %MEM VSZ RSS TT STAT STARTED TIME COMMAND
                  100 3304 0.0 0.2 2466308 6476 ?? Ss 2Sep12 0:01.75 /usr/bin/someApp





                  share|improve this answer












                  Perhaps two ps commands would be easiest.



                  $ ps aux | head -1 && ps aux | grep someApp
                  USER PID %CPU %MEM VSZ RSS TT STAT STARTED TIME COMMAND
                  100 3304 0.0 0.2 2466308 6476 ?? Ss 2Sep12 0:01.75 /usr/bin/someApp






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Sep 12 '12 at 11:08









                  emcconville

                  26626




                  26626







                  • 2




                    I don't like this solution, primarily because the situation could change between the first and second ps aux call... And if you just want that static first line, why not echo it manually?
                    – Shadur
                    Sep 12 '12 at 11:19






                  • 1




                    Changes between the two calls aren't to be bothered in this situation. The first will only provide the headline which will always fit to the output of the second.
                    – Alfe
                    Sep 12 '12 at 13:30







                  • 2




                    I don't see why this was downvoted, it certainly is a viable option. Upvoting.
                    – dotancohen
                    Sep 12 '12 at 14:37












                  • 2




                    I don't like this solution, primarily because the situation could change between the first and second ps aux call... And if you just want that static first line, why not echo it manually?
                    – Shadur
                    Sep 12 '12 at 11:19






                  • 1




                    Changes between the two calls aren't to be bothered in this situation. The first will only provide the headline which will always fit to the output of the second.
                    – Alfe
                    Sep 12 '12 at 13:30







                  • 2




                    I don't see why this was downvoted, it certainly is a viable option. Upvoting.
                    – dotancohen
                    Sep 12 '12 at 14:37







                  2




                  2




                  I don't like this solution, primarily because the situation could change between the first and second ps aux call... And if you just want that static first line, why not echo it manually?
                  – Shadur
                  Sep 12 '12 at 11:19




                  I don't like this solution, primarily because the situation could change between the first and second ps aux call... And if you just want that static first line, why not echo it manually?
                  – Shadur
                  Sep 12 '12 at 11:19




                  1




                  1




                  Changes between the two calls aren't to be bothered in this situation. The first will only provide the headline which will always fit to the output of the second.
                  – Alfe
                  Sep 12 '12 at 13:30





                  Changes between the two calls aren't to be bothered in this situation. The first will only provide the headline which will always fit to the output of the second.
                  – Alfe
                  Sep 12 '12 at 13:30





                  2




                  2




                  I don't see why this was downvoted, it certainly is a viable option. Upvoting.
                  – dotancohen
                  Sep 12 '12 at 14:37




                  I don't see why this was downvoted, it certainly is a viable option. Upvoting.
                  – dotancohen
                  Sep 12 '12 at 14:37










                  up vote
                  4
                  down vote













                  You could use pidstat with:



                  pidstat -C someApp
                  or
                  pidstat -p <PID>


                  Example:



                  # pidstat -C java
                  Linux 3.0.26-0.7-default (hostname) 09/12/12 _x86_64_

                  13:41:21 PID %usr %system %guest %CPU CPU Command
                  13:41:21 3671 0.07 0.02 0.00 0.09 1 java


                  Further Info:
                  http://linux.die.net/man/1/pidstat






                  share|improve this answer




















                  • Thanks, that is nice to know. However, it won't find scripts started from python, among others.
                    – dotancohen
                    Sep 12 '12 at 14:35














                  up vote
                  4
                  down vote













                  You could use pidstat with:



                  pidstat -C someApp
                  or
                  pidstat -p <PID>


                  Example:



                  # pidstat -C java
                  Linux 3.0.26-0.7-default (hostname) 09/12/12 _x86_64_

                  13:41:21 PID %usr %system %guest %CPU CPU Command
                  13:41:21 3671 0.07 0.02 0.00 0.09 1 java


                  Further Info:
                  http://linux.die.net/man/1/pidstat






                  share|improve this answer




















                  • Thanks, that is nice to know. However, it won't find scripts started from python, among others.
                    – dotancohen
                    Sep 12 '12 at 14:35












                  up vote
                  4
                  down vote










                  up vote
                  4
                  down vote









                  You could use pidstat with:



                  pidstat -C someApp
                  or
                  pidstat -p <PID>


                  Example:



                  # pidstat -C java
                  Linux 3.0.26-0.7-default (hostname) 09/12/12 _x86_64_

                  13:41:21 PID %usr %system %guest %CPU CPU Command
                  13:41:21 3671 0.07 0.02 0.00 0.09 1 java


                  Further Info:
                  http://linux.die.net/man/1/pidstat






                  share|improve this answer












                  You could use pidstat with:



                  pidstat -C someApp
                  or
                  pidstat -p <PID>


                  Example:



                  # pidstat -C java
                  Linux 3.0.26-0.7-default (hostname) 09/12/12 _x86_64_

                  13:41:21 PID %usr %system %guest %CPU CPU Command
                  13:41:21 3671 0.07 0.02 0.00 0.09 1 java


                  Further Info:
                  http://linux.die.net/man/1/pidstat







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Sep 12 '12 at 11:42









                  harp

                  5652715




                  5652715











                  • Thanks, that is nice to know. However, it won't find scripts started from python, among others.
                    – dotancohen
                    Sep 12 '12 at 14:35
















                  • Thanks, that is nice to know. However, it won't find scripts started from python, among others.
                    – dotancohen
                    Sep 12 '12 at 14:35















                  Thanks, that is nice to know. However, it won't find scripts started from python, among others.
                  – dotancohen
                  Sep 12 '12 at 14:35




                  Thanks, that is nice to know. However, it won't find scripts started from python, among others.
                  – dotancohen
                  Sep 12 '12 at 14:35










                  up vote
                  4
                  down vote













                  Put the following in your .bashrc file or copy/paste in shell first, for testing.



                  function psls grep "$1"


                  Usage: psls [grep pattern]



                  $ psls someApp
                  USER PID %CPU %MEM VSZ RSS TT STAT STARTED TIME COMMAND
                  root 21 0.0 0.0 2467312 1116 ?? Ss Tue07PM 0:00.17 /sbin/someApp


                  Make sure to source your .bashrc (or .bash_profile if you put it there instead):



                  source ~/.bashrc


                  The function will even auto-complete at the shell command line. As you stated in another answer, you can pipe the first line to a file to save one call to ps.






                  share|improve this answer






















                  • Nice, I've been using that kind of function for years. I call my version psl, which only call ps and grep once each (and doesn't need head).
                    – Adam Katz
                    Jan 14 '15 at 21:08















                  up vote
                  4
                  down vote













                  Put the following in your .bashrc file or copy/paste in shell first, for testing.



                  function psls grep "$1"


                  Usage: psls [grep pattern]



                  $ psls someApp
                  USER PID %CPU %MEM VSZ RSS TT STAT STARTED TIME COMMAND
                  root 21 0.0 0.0 2467312 1116 ?? Ss Tue07PM 0:00.17 /sbin/someApp


                  Make sure to source your .bashrc (or .bash_profile if you put it there instead):



                  source ~/.bashrc


                  The function will even auto-complete at the shell command line. As you stated in another answer, you can pipe the first line to a file to save one call to ps.






                  share|improve this answer






















                  • Nice, I've been using that kind of function for years. I call my version psl, which only call ps and grep once each (and doesn't need head).
                    – Adam Katz
                    Jan 14 '15 at 21:08













                  up vote
                  4
                  down vote










                  up vote
                  4
                  down vote









                  Put the following in your .bashrc file or copy/paste in shell first, for testing.



                  function psls grep "$1"


                  Usage: psls [grep pattern]



                  $ psls someApp
                  USER PID %CPU %MEM VSZ RSS TT STAT STARTED TIME COMMAND
                  root 21 0.0 0.0 2467312 1116 ?? Ss Tue07PM 0:00.17 /sbin/someApp


                  Make sure to source your .bashrc (or .bash_profile if you put it there instead):



                  source ~/.bashrc


                  The function will even auto-complete at the shell command line. As you stated in another answer, you can pipe the first line to a file to save one call to ps.






                  share|improve this answer














                  Put the following in your .bashrc file or copy/paste in shell first, for testing.



                  function psls grep "$1"


                  Usage: psls [grep pattern]



                  $ psls someApp
                  USER PID %CPU %MEM VSZ RSS TT STAT STARTED TIME COMMAND
                  root 21 0.0 0.0 2467312 1116 ?? Ss Tue07PM 0:00.17 /sbin/someApp


                  Make sure to source your .bashrc (or .bash_profile if you put it there instead):



                  source ~/.bashrc


                  The function will even auto-complete at the shell command line. As you stated in another answer, you can pipe the first line to a file to save one call to ps.







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Sep 13 '12 at 4:31

























                  answered Sep 13 '12 at 4:05









                  taco

                  1433




                  1433











                  • Nice, I've been using that kind of function for years. I call my version psl, which only call ps and grep once each (and doesn't need head).
                    – Adam Katz
                    Jan 14 '15 at 21:08

















                  • Nice, I've been using that kind of function for years. I call my version psl, which only call ps and grep once each (and doesn't need head).
                    – Adam Katz
                    Jan 14 '15 at 21:08
















                  Nice, I've been using that kind of function for years. I call my version psl, which only call ps and grep once each (and doesn't need head).
                  – Adam Katz
                  Jan 14 '15 at 21:08





                  Nice, I've been using that kind of function for years. I call my version psl, which only call ps and grep once each (and doesn't need head).
                  – Adam Katz
                  Jan 14 '15 at 21:08











                  up vote
                  3
                  down vote













                  sort but keep header line at the top



                  # print the header (the first line of input)
                  # and then run the specified command on the body (the rest of the input)
                  # use it in a pipeline, e.g. ps | body grep somepattern
                  body()
                  IFS= read -r header
                  printf '%sn' "$header"
                  "$@"



                  And use it like this



                  $ ps aux | body grep someApp
                  USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
                  1000 11634 51.2 0.1 32824 9112 pts/1 SN+ 13:24 7:49 someApp





                  share|improve this answer






















                  • Thanks, some of those answers discuss the general case of this question. Perfect!
                    – dotancohen
                    Sep 13 '12 at 10:07














                  up vote
                  3
                  down vote













                  sort but keep header line at the top



                  # print the header (the first line of input)
                  # and then run the specified command on the body (the rest of the input)
                  # use it in a pipeline, e.g. ps | body grep somepattern
                  body()
                  IFS= read -r header
                  printf '%sn' "$header"
                  "$@"



                  And use it like this



                  $ ps aux | body grep someApp
                  USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
                  1000 11634 51.2 0.1 32824 9112 pts/1 SN+ 13:24 7:49 someApp





                  share|improve this answer






















                  • Thanks, some of those answers discuss the general case of this question. Perfect!
                    – dotancohen
                    Sep 13 '12 at 10:07












                  up vote
                  3
                  down vote










                  up vote
                  3
                  down vote









                  sort but keep header line at the top



                  # print the header (the first line of input)
                  # and then run the specified command on the body (the rest of the input)
                  # use it in a pipeline, e.g. ps | body grep somepattern
                  body()
                  IFS= read -r header
                  printf '%sn' "$header"
                  "$@"



                  And use it like this



                  $ ps aux | body grep someApp
                  USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
                  1000 11634 51.2 0.1 32824 9112 pts/1 SN+ 13:24 7:49 someApp





                  share|improve this answer














                  sort but keep header line at the top



                  # print the header (the first line of input)
                  # and then run the specified command on the body (the rest of the input)
                  # use it in a pipeline, e.g. ps | body grep somepattern
                  body()
                  IFS= read -r header
                  printf '%sn' "$header"
                  "$@"



                  And use it like this



                  $ ps aux | body grep someApp
                  USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
                  1000 11634 51.2 0.1 32824 9112 pts/1 SN+ 13:24 7:49 someApp






                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Apr 13 '17 at 12:36









                  Community♦

                  1




                  1










                  answered Sep 13 '12 at 4:41









                  Mikel

                  38.1k996123




                  38.1k996123











                  • Thanks, some of those answers discuss the general case of this question. Perfect!
                    – dotancohen
                    Sep 13 '12 at 10:07
















                  • Thanks, some of those answers discuss the general case of this question. Perfect!
                    – dotancohen
                    Sep 13 '12 at 10:07















                  Thanks, some of those answers discuss the general case of this question. Perfect!
                  – dotancohen
                  Sep 13 '12 at 10:07




                  Thanks, some of those answers discuss the general case of this question. Perfect!
                  – dotancohen
                  Sep 13 '12 at 10:07










                  up vote
                  2
                  down vote













                  Another way with gnu ed:



                  ed -s '!ps aux' <<< $'2,$v/PATTERN/dn,pnqn'


                  or, if the shell supports process substitution:



                  printf '%sn' '2,$v/PATTERN/d' ,p q | ed -s <(ps aux)


                  that is:



                  2,$v/PATTERN/d - remove all lines not matching pattern (ignore the header)
                  ,p - print the remaining lines
                  q - quit


                  More portable, without gnu '!' or shell substitution - using only ed built-in r to read the output of ps aux into the buffer and then delete non-matching lines in the 2,$ range and print the result:



                  printf '%sn' 'r !ps aux' '2,$v/PATTERN/d' ,p q | ed -s



                  And since the sed commands in the accepted answer output also the line matching themselves, with a sed that supports -f- and a shell that supports process substitution I would run:



                  printf '%sn' '2,$' '/PATTERN/!d' '' | sed -f - <(ps aux)


                  which pretty much does the same thing as the previous ed commands.






                  share|improve this answer


























                    up vote
                    2
                    down vote













                    Another way with gnu ed:



                    ed -s '!ps aux' <<< $'2,$v/PATTERN/dn,pnqn'


                    or, if the shell supports process substitution:



                    printf '%sn' '2,$v/PATTERN/d' ,p q | ed -s <(ps aux)


                    that is:



                    2,$v/PATTERN/d - remove all lines not matching pattern (ignore the header)
                    ,p - print the remaining lines
                    q - quit


                    More portable, without gnu '!' or shell substitution - using only ed built-in r to read the output of ps aux into the buffer and then delete non-matching lines in the 2,$ range and print the result:



                    printf '%sn' 'r !ps aux' '2,$v/PATTERN/d' ,p q | ed -s



                    And since the sed commands in the accepted answer output also the line matching themselves, with a sed that supports -f- and a shell that supports process substitution I would run:



                    printf '%sn' '2,$' '/PATTERN/!d' '' | sed -f - <(ps aux)


                    which pretty much does the same thing as the previous ed commands.






                    share|improve this answer
























                      up vote
                      2
                      down vote










                      up vote
                      2
                      down vote









                      Another way with gnu ed:



                      ed -s '!ps aux' <<< $'2,$v/PATTERN/dn,pnqn'


                      or, if the shell supports process substitution:



                      printf '%sn' '2,$v/PATTERN/d' ,p q | ed -s <(ps aux)


                      that is:



                      2,$v/PATTERN/d - remove all lines not matching pattern (ignore the header)
                      ,p - print the remaining lines
                      q - quit


                      More portable, without gnu '!' or shell substitution - using only ed built-in r to read the output of ps aux into the buffer and then delete non-matching lines in the 2,$ range and print the result:



                      printf '%sn' 'r !ps aux' '2,$v/PATTERN/d' ,p q | ed -s



                      And since the sed commands in the accepted answer output also the line matching themselves, with a sed that supports -f- and a shell that supports process substitution I would run:



                      printf '%sn' '2,$' '/PATTERN/!d' '' | sed -f - <(ps aux)


                      which pretty much does the same thing as the previous ed commands.






                      share|improve this answer














                      Another way with gnu ed:



                      ed -s '!ps aux' <<< $'2,$v/PATTERN/dn,pnqn'


                      or, if the shell supports process substitution:



                      printf '%sn' '2,$v/PATTERN/d' ,p q | ed -s <(ps aux)


                      that is:



                      2,$v/PATTERN/d - remove all lines not matching pattern (ignore the header)
                      ,p - print the remaining lines
                      q - quit


                      More portable, without gnu '!' or shell substitution - using only ed built-in r to read the output of ps aux into the buffer and then delete non-matching lines in the 2,$ range and print the result:



                      printf '%sn' 'r !ps aux' '2,$v/PATTERN/d' ,p q | ed -s



                      And since the sed commands in the accepted answer output also the line matching themselves, with a sed that supports -f- and a shell that supports process substitution I would run:



                      printf '%sn' '2,$' '/PATTERN/!d' '' | sed -f - <(ps aux)


                      which pretty much does the same thing as the previous ed commands.







                      share|improve this answer














                      share|improve this answer



                      share|improve this answer








                      edited Aug 2 '15 at 18:53


























                      community wiki





                      3 revs
                      don_crissti





















                          up vote
                          1
                          down vote













                          I’m using zsh and this function works well for me:



                          function grep1() grep $*)



                          The main advantage of this approach is that you have full control over the grep command, so you can pass the usual flags like -i, -E, etc.



                          Usage example:



                          $ ps -rcA | grep1 databases
                          PID TTY TIME CMD

                          $ ps -rcA | grep1 -i databases
                          PID TTY TIME CMD
                          62891 ?? 0:00.33 com.apple.WebKit.Databases





                          share|improve this answer
























                            up vote
                            1
                            down vote













                            I’m using zsh and this function works well for me:



                            function grep1() grep $*)



                            The main advantage of this approach is that you have full control over the grep command, so you can pass the usual flags like -i, -E, etc.



                            Usage example:



                            $ ps -rcA | grep1 databases
                            PID TTY TIME CMD

                            $ ps -rcA | grep1 -i databases
                            PID TTY TIME CMD
                            62891 ?? 0:00.33 com.apple.WebKit.Databases





                            share|improve this answer






















                              up vote
                              1
                              down vote










                              up vote
                              1
                              down vote









                              I’m using zsh and this function works well for me:



                              function grep1() grep $*)



                              The main advantage of this approach is that you have full control over the grep command, so you can pass the usual flags like -i, -E, etc.



                              Usage example:



                              $ ps -rcA | grep1 databases
                              PID TTY TIME CMD

                              $ ps -rcA | grep1 -i databases
                              PID TTY TIME CMD
                              62891 ?? 0:00.33 com.apple.WebKit.Databases





                              share|improve this answer












                              I’m using zsh and this function works well for me:



                              function grep1() grep $*)



                              The main advantage of this approach is that you have full control over the grep command, so you can pass the usual flags like -i, -E, etc.



                              Usage example:



                              $ ps -rcA | grep1 databases
                              PID TTY TIME CMD

                              $ ps -rcA | grep1 -i databases
                              PID TTY TIME CMD
                              62891 ?? 0:00.33 com.apple.WebKit.Databases






                              share|improve this answer












                              share|improve this answer



                              share|improve this answer










                              answered Apr 27 '16 at 14:55









                              bdesham

                              284211




                              284211




















                                  up vote
                                  1
                                  down vote













                                  The Perl way:



                                  ps aux | perl -ne 'print if /pattern/ || $.==1'


                                  Way easier to read than sed, faster, no risk to pick undesired lines.






                                  share|improve this answer






















                                  • Perl?!?
                                    – dotancohen
                                    Sep 23 '16 at 8:01














                                  up vote
                                  1
                                  down vote













                                  The Perl way:



                                  ps aux | perl -ne 'print if /pattern/ || $.==1'


                                  Way easier to read than sed, faster, no risk to pick undesired lines.






                                  share|improve this answer






















                                  • Perl?!?
                                    – dotancohen
                                    Sep 23 '16 at 8:01












                                  up vote
                                  1
                                  down vote










                                  up vote
                                  1
                                  down vote









                                  The Perl way:



                                  ps aux | perl -ne 'print if /pattern/ || $.==1'


                                  Way easier to read than sed, faster, no risk to pick undesired lines.






                                  share|improve this answer














                                  The Perl way:



                                  ps aux | perl -ne 'print if /pattern/ || $.==1'


                                  Way easier to read than sed, faster, no risk to pick undesired lines.







                                  share|improve this answer














                                  share|improve this answer



                                  share|improve this answer








                                  edited Sep 29 '16 at 15:13

























                                  answered Sep 23 '16 at 2:51









                                  emazep

                                  1113




                                  1113











                                  • Perl?!?
                                    – dotancohen
                                    Sep 23 '16 at 8:01
















                                  • Perl?!?
                                    – dotancohen
                                    Sep 23 '16 at 8:01















                                  Perl?!?
                                  – dotancohen
                                  Sep 23 '16 at 8:01




                                  Perl?!?
                                  – dotancohen
                                  Sep 23 '16 at 8:01










                                  up vote
                                  0
                                  down vote













                                  If that's only for grepping processes with full headers, I'd expand @mrb's suggestion:



                                  $ ps -f -p $(pgrep bash)
                                  UID PID PPID C STIME TTY STAT TIME CMD
                                  nasha 2810 2771 0 2014 pts/6 Ss+ 0:00 bash
                                  ...


                                  pgrep bash | xargs ps -fp will get the same result but without a subshell. If other formatting is required:



                                  $ pgrep bash | xargs ps fo uid,pid,stime,cmd -p
                                  UID PID STIME CMD
                                  0 3599 2014 -bash
                                  1000 3286 2014 /bin/bash
                                  ...





                                  share|improve this answer


























                                    up vote
                                    0
                                    down vote













                                    If that's only for grepping processes with full headers, I'd expand @mrb's suggestion:



                                    $ ps -f -p $(pgrep bash)
                                    UID PID PPID C STIME TTY STAT TIME CMD
                                    nasha 2810 2771 0 2014 pts/6 Ss+ 0:00 bash
                                    ...


                                    pgrep bash | xargs ps -fp will get the same result but without a subshell. If other formatting is required:



                                    $ pgrep bash | xargs ps fo uid,pid,stime,cmd -p
                                    UID PID STIME CMD
                                    0 3599 2014 -bash
                                    1000 3286 2014 /bin/bash
                                    ...





                                    share|improve this answer
























                                      up vote
                                      0
                                      down vote










                                      up vote
                                      0
                                      down vote









                                      If that's only for grepping processes with full headers, I'd expand @mrb's suggestion:



                                      $ ps -f -p $(pgrep bash)
                                      UID PID PPID C STIME TTY STAT TIME CMD
                                      nasha 2810 2771 0 2014 pts/6 Ss+ 0:00 bash
                                      ...


                                      pgrep bash | xargs ps -fp will get the same result but without a subshell. If other formatting is required:



                                      $ pgrep bash | xargs ps fo uid,pid,stime,cmd -p
                                      UID PID STIME CMD
                                      0 3599 2014 -bash
                                      1000 3286 2014 /bin/bash
                                      ...





                                      share|improve this answer














                                      If that's only for grepping processes with full headers, I'd expand @mrb's suggestion:



                                      $ ps -f -p $(pgrep bash)
                                      UID PID PPID C STIME TTY STAT TIME CMD
                                      nasha 2810 2771 0 2014 pts/6 Ss+ 0:00 bash
                                      ...


                                      pgrep bash | xargs ps -fp will get the same result but without a subshell. If other formatting is required:



                                      $ pgrep bash | xargs ps fo uid,pid,stime,cmd -p
                                      UID PID STIME CMD
                                      0 3599 2014 -bash
                                      1000 3286 2014 /bin/bash
                                      ...






                                      share|improve this answer














                                      share|improve this answer



                                      share|improve this answer








                                      edited Jan 1 '15 at 14:00

























                                      answered Jan 1 '15 at 13:55







                                      user86969



























                                          up vote
                                          -1
                                          down vote













                                          If you know the exact line numbers, it's easy with perl! If you want to get line 1 and 5 from a file, say /etc/passwd:



                                          perl -e 'while(<>)if(++$l~~[1,5])print' < /etc/passwd


                                          If you want to get other lines too, just add their numbers in the array.






                                          share|improve this answer


















                                          • 1




                                            Thank you. As per the OP, I know some of the text in the line, but not the line number.
                                            – dotancohen
                                            Mar 23 '16 at 14:46











                                          • This pops up as an answer on Google when looking for this use case closely related to the OP, so worth noting here.
                                            – Dagelf
                                            Mar 23 '16 at 15:19






                                          • 1




                                            If that is the case, then I highly suggest that you start a new question and answer it with this answer. It is perfectly fine to answer your own questions on SE, especially in the situation that you mention. Go ahead and link to your new question in a comment on the OP.
                                            – dotancohen
                                            Mar 23 '16 at 15:37










                                          • There are such questions, but they don't currently pop up on Google.
                                            – Dagelf
                                            Mar 25 '16 at 13:38










                                          • Dagelf, bottom line is - your answer doesn't answer the question here. @dotancohen is right - if this pops up as an answer on Google when looking for this use case closely related to the OP then ask a separate question - detailing that closely related use case - and answer it.
                                            – don_crissti
                                            Mar 25 '16 at 13:56














                                          up vote
                                          -1
                                          down vote













                                          If you know the exact line numbers, it's easy with perl! If you want to get line 1 and 5 from a file, say /etc/passwd:



                                          perl -e 'while(<>)if(++$l~~[1,5])print' < /etc/passwd


                                          If you want to get other lines too, just add their numbers in the array.






                                          share|improve this answer


















                                          • 1




                                            Thank you. As per the OP, I know some of the text in the line, but not the line number.
                                            – dotancohen
                                            Mar 23 '16 at 14:46











                                          • This pops up as an answer on Google when looking for this use case closely related to the OP, so worth noting here.
                                            – Dagelf
                                            Mar 23 '16 at 15:19






                                          • 1




                                            If that is the case, then I highly suggest that you start a new question and answer it with this answer. It is perfectly fine to answer your own questions on SE, especially in the situation that you mention. Go ahead and link to your new question in a comment on the OP.
                                            – dotancohen
                                            Mar 23 '16 at 15:37










                                          • There are such questions, but they don't currently pop up on Google.
                                            – Dagelf
                                            Mar 25 '16 at 13:38










                                          • Dagelf, bottom line is - your answer doesn't answer the question here. @dotancohen is right - if this pops up as an answer on Google when looking for this use case closely related to the OP then ask a separate question - detailing that closely related use case - and answer it.
                                            – don_crissti
                                            Mar 25 '16 at 13:56












                                          up vote
                                          -1
                                          down vote










                                          up vote
                                          -1
                                          down vote









                                          If you know the exact line numbers, it's easy with perl! If you want to get line 1 and 5 from a file, say /etc/passwd:



                                          perl -e 'while(<>)if(++$l~~[1,5])print' < /etc/passwd


                                          If you want to get other lines too, just add their numbers in the array.






                                          share|improve this answer














                                          If you know the exact line numbers, it's easy with perl! If you want to get line 1 and 5 from a file, say /etc/passwd:



                                          perl -e 'while(<>)if(++$l~~[1,5])print' < /etc/passwd


                                          If you want to get other lines too, just add their numbers in the array.







                                          share|improve this answer














                                          share|improve this answer



                                          share|improve this answer








                                          edited Mar 25 '16 at 13:40

























                                          answered Mar 23 '16 at 13:35









                                          Dagelf

                                          993




                                          993







                                          • 1




                                            Thank you. As per the OP, I know some of the text in the line, but not the line number.
                                            – dotancohen
                                            Mar 23 '16 at 14:46











                                          • This pops up as an answer on Google when looking for this use case closely related to the OP, so worth noting here.
                                            – Dagelf
                                            Mar 23 '16 at 15:19






                                          • 1




                                            If that is the case, then I highly suggest that you start a new question and answer it with this answer. It is perfectly fine to answer your own questions on SE, especially in the situation that you mention. Go ahead and link to your new question in a comment on the OP.
                                            – dotancohen
                                            Mar 23 '16 at 15:37










                                          • There are such questions, but they don't currently pop up on Google.
                                            – Dagelf
                                            Mar 25 '16 at 13:38










                                          • Dagelf, bottom line is - your answer doesn't answer the question here. @dotancohen is right - if this pops up as an answer on Google when looking for this use case closely related to the OP then ask a separate question - detailing that closely related use case - and answer it.
                                            – don_crissti
                                            Mar 25 '16 at 13:56












                                          • 1




                                            Thank you. As per the OP, I know some of the text in the line, but not the line number.
                                            – dotancohen
                                            Mar 23 '16 at 14:46











                                          • This pops up as an answer on Google when looking for this use case closely related to the OP, so worth noting here.
                                            – Dagelf
                                            Mar 23 '16 at 15:19






                                          • 1




                                            If that is the case, then I highly suggest that you start a new question and answer it with this answer. It is perfectly fine to answer your own questions on SE, especially in the situation that you mention. Go ahead and link to your new question in a comment on the OP.
                                            – dotancohen
                                            Mar 23 '16 at 15:37










                                          • There are such questions, but they don't currently pop up on Google.
                                            – Dagelf
                                            Mar 25 '16 at 13:38










                                          • Dagelf, bottom line is - your answer doesn't answer the question here. @dotancohen is right - if this pops up as an answer on Google when looking for this use case closely related to the OP then ask a separate question - detailing that closely related use case - and answer it.
                                            – don_crissti
                                            Mar 25 '16 at 13:56







                                          1




                                          1




                                          Thank you. As per the OP, I know some of the text in the line, but not the line number.
                                          – dotancohen
                                          Mar 23 '16 at 14:46





                                          Thank you. As per the OP, I know some of the text in the line, but not the line number.
                                          – dotancohen
                                          Mar 23 '16 at 14:46













                                          This pops up as an answer on Google when looking for this use case closely related to the OP, so worth noting here.
                                          – Dagelf
                                          Mar 23 '16 at 15:19




                                          This pops up as an answer on Google when looking for this use case closely related to the OP, so worth noting here.
                                          – Dagelf
                                          Mar 23 '16 at 15:19




                                          1




                                          1




                                          If that is the case, then I highly suggest that you start a new question and answer it with this answer. It is perfectly fine to answer your own questions on SE, especially in the situation that you mention. Go ahead and link to your new question in a comment on the OP.
                                          – dotancohen
                                          Mar 23 '16 at 15:37




                                          If that is the case, then I highly suggest that you start a new question and answer it with this answer. It is perfectly fine to answer your own questions on SE, especially in the situation that you mention. Go ahead and link to your new question in a comment on the OP.
                                          – dotancohen
                                          Mar 23 '16 at 15:37












                                          There are such questions, but they don't currently pop up on Google.
                                          – Dagelf
                                          Mar 25 '16 at 13:38




                                          There are such questions, but they don't currently pop up on Google.
                                          – Dagelf
                                          Mar 25 '16 at 13:38












                                          Dagelf, bottom line is - your answer doesn't answer the question here. @dotancohen is right - if this pops up as an answer on Google when looking for this use case closely related to the OP then ask a separate question - detailing that closely related use case - and answer it.
                                          – don_crissti
                                          Mar 25 '16 at 13:56




                                          Dagelf, bottom line is - your answer doesn't answer the question here. @dotancohen is right - if this pops up as an answer on Google when looking for this use case closely related to the OP then ask a separate question - detailing that closely related use case - and answer it.
                                          – don_crissti
                                          Mar 25 '16 at 13:56

















                                           

                                          draft saved


                                          draft discarded















































                                           


                                          draft saved


                                          draft discarded














                                          StackExchange.ready(
                                          function ()
                                          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2funix.stackexchange.com%2fquestions%2f47918%2fhow-to-grep-a-specific-line-and-the-first-line-of-a-file%23new-answer', 'question_page');

                                          );

                                          Post as a guest













































































                                          Popular posts from this blog

                                          Peggy Mitchell

                                          Palaiologos

                                          The Forum (Inglewood, California)