0

I have a list of "tasks" which I go through to learn the shell-code, I need to use grep to isolate the line in /etc/passwd that contains “ubu”. I know that the command less /etc/passwd is used to access /etc/passwd, and that grep is used to find/search for a certain string pattern, but that's about it

1

With grep:

$ grep -F "ubu" /etc/passwd

This uses grep -F to search for the literal string ubu in the file /etc/passwd. Without the -F, grep would treat ubu as a regular expression. In this case it wouldn't make a difference, but if the string contained characters, like *, which is "special" in regular expressions, then this is how you could make them "less special".

grep will return all lines that contains the match.

If ubu is a username (a complete username, not just a part of one), then the following will additionally do a lookup in any directory service (like LDAP or NIS/YP) that the system may be using:

$ getent passwd ubu
  • Also if I want to search for a string in the /home directory,can I do it the same way? or is there anything else to it? – Ahmad Khateeb May 24 '17 at 6:41
  • @AhmadKhateeb In all files under /home? Try find /home -type f -exec grep -HF "ubu" {} + (see the manual for grep for the -H flag). – Kusalananda May 24 '17 at 6:45
  • @AhmadKahateeb You have to use find here because you are searching in a directory and not in a single file or in a small set of files that you can list on the command line. – Kusalananda May 24 '17 at 6:53
  • 1
    Or see if your grep supports the -r option for recursive search (FreeBSD and GNU grep do) – Philippos May 24 '17 at 7:51
  • @Philippos Yes, I don't know why I didn't think about that... – Kusalananda May 24 '17 at 7:52
1

You should probably start with a tutorial to learn the basics.

If you simply looked for grep's man page, you would have been able to figure it out quite easily.

You can basically do grep "ubu" /etc/passwd.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.