working with grep with examples

  1. Find all users who have /bin/bash as shell and write it to /home/dipika/users_with_bash.txt
    grep “/bin/bash” /etc/passwd > /home/dipika/users_with_bash.txt
  2. Find if the user Reewa or reewa exist in system and write the list to /home/dipika/users.txt
    grep -w ‘[Rr]eewa’ /etc/passwd > /home/dipika/users.txt
    grep -i ‘reewa’ /etc/passwd > /home/dipika/users.txt
    grep -i ‘^reewa’ /etc/passwd > /home/dipika/users.txthints: -w is used to find out exact work match. -i is used for case insensitive search and [Rr] will search for either R or r in first position, in given example. Similarly, ^ sign in last example indicates that reewa should be at the begining of line. so it will only match reewa in username, if for example a person has rtamrakar as username and reewa tamrakar as full name (GECOS), then it will not match that. I prefer third example, which gives accurate result. 
  3. Find all users who have /sbin/nologin as shell and write only username and home directory to /users_with_nologin.
    grep ‘/sbin/nologin$’ /etc/passwd|cut -d: -f1,6 > /users_with_nologin
  4. Find all normal users whose uid/gid are 1000 or above and write the result to /users_with_id_above_1000.txt.
    grep ‘[1-9][0-9][0-9][0-9]’ /etc/passwd /users_with_id_above_1000.txt
    hints: [ ] are used to find out the matches, where each box [ ] represent 1 digit so, first digit should be 1 to 9, and rest should be 0 to 9. Plese remrmber that, were are matching digits assuming that only uid and gid will have digits. 
  5. Find all users whose first three characters are ree, 4th character can be any and the 5th/last character should be a.
    grep ‘^ree.a’ /etc/passwd
        hints: . can be use to represent single character. 
  6. Match word reewa or reeva in /etc/passwd and write it to /root/reewa_reeva.txt
    egrep ‘(reewa|reeva)’ /etc/passwd > /root/reewa_reeva.txt
    hints: egrep support additional parameters, one example is ussing or operator in () like in example above

    echo reewa >/a.txt
    echo reeva >> /a.txt
    grep -f /a.txt /etc/passwd > /root/reewa_reeva.txt
  7. Find name rewa or reewa in /etc/passwd
    egrep ‘re{1,2}wa’ /etc/passwd
    hints: {min,max } will match sequence of characters. In above example e{1,2} will mtch e or ee, i.e 1 or 2 e.

Leave a Reply

Your email address will not be published.

− three = 5

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Recent Posts
Recent Comments
    Updates on Recent activieies