How to use grep command to list dot based names

Viewed 73

I am trying to grep some of the services but it does not print exactly what I am looking for.

One thing I see in the grep strings is that the names are having dot . jointed names.

I am trying below but not getting the desired output.

# systemctl list-unit-files | egrep -w "autofs.service|sssd.service"
autofs.service                                disabled
sssd-autofs.service                           indirect
sssd.service                                  disabled

or

# systemctl list-unit-files | egrep "autofs|sssd[.service]"
autofs.service                                disabled
sssd-autofs.service                           indirect
sssd.service                                  disabled
sssd-autofs.socket                            disabled

Expected Output:

# systemctl list-unit-files | egrep -w "autofs.service|sssd.service"
autofs.service                                disabled
sssd.service                                  disabled
2 Answers

You can use

grep -E '^(sssd|autofs)\.service'

Here,

  • ^ - start of string
  • (sssd|autofs) - a group matching either of the two substrings
  • \.service - a .service substring.

See an online demo.

Use grep with -P option for Perl regexes, parentheses to group the patterns, and (optionally in your case) \. or [.] to match a literal period, rather than special character ., which matches any character:

grep -P "(autofs[.]service|sssd[.]service)"
Related