0

Can you explain in detail what happened here on this command?

grep -nw '^root' /etc/passwd

What is the use of ^ and '? Please give me examples and be detailed cuz all I'm hearing is that it's the beginning of the line. I don't understand what each of those special characters means.

How would I go about using wc, grep and ^ to find out the number of non-root processes running on my system?

user6260366
  • 47
  • 1
  • 7
  • Have you looked at the manual page for `grep`? It's explained there. Once you understand that, look at the manual page for `wc`. Then you can probably answer your last question yourself. – lurker Apr 28 '16 at 17:00
  • 1
    These mysterious thing inside the quotes is a `regular expression`. Information can be found e.g. here: http://stackoverflow.com/questions/22937618/reference-what-does-this-regex-mean/22944075#22944075 – Lars Fischer Apr 28 '16 at 17:11
  • Check the man page if in doubt. It's made for that – hek2mgl Apr 28 '16 at 21:44

1 Answers1

0
grep -nw '^root' /etc/passwd

It reads the /etc/passwd file line-by-line and filters out all those lines that ^=begin with the -w=complete word "root". So, for example the line

root:x:0:0:root:/root:/bin/bash

To see all processes on a system, you could use ps aux. and it will show lines like this

root 22866  0.0 [...] 0:00 [kworker/1:0]

As you can see, the lines start with a username. If you pipe the ps aux output through grep, you can use the same RegEx from above, to filter out all lines that do not start with "root".

Use -v to invert pattern matching, so that grep -vw '^root' finds all lines that don't begin with a complete word "root".

ps aux | grep -vw '^root' | wc -l

Finally, wc -l counts the number of lines it receives. So that is the number of all lines from ps aux that do not begin with "root".

C14L
  • 12,153
  • 4
  • 39
  • 52