0

for a line in /etc/passwd

I want to grep from end of line ($) to the first ":" from the end of the line.

For example,\n johndoe:x:39:39:John Doe:/var/lib/canna:/sbin/nologin

I want to grep "/sbin/nologin"

What is the right regex to use for my grep command?

namesake22
  • 345
  • 2
  • 12

2 Answers2

1

If you don't mind the colon being selected too, then use:

grep -o -e ':[^:]*$' /etc/passwd

That selects a colon not followed by any other colon and then end of line and only print what matches.

If you don't want the colon and you do have a PCRE-enabled grep, look at Regex lookahead for 'not followed by' in grep?; you'll need to adapt it to do look-behind instead of look-ahead, that's all.

If you don't have grep with -o, use sed instead (omitting the colon):

sed -n -e '/.*:\([^:]*\)$/ s//\1/p' /etc/passwd

This is probably the most portable solution.

(On macOS Sierra, and Mac OS X, the /etc/passwd file has comment lines at the top starting with a #. The sed command does not print those lines because they don't have any colons on them. This works cleanly on Macs as well as Linux and other variants of Unix, therefore. It uses no advanced (aka non-portable) features of sed.)

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
1

How about use cut, This is more straight for this:

echo 'johndoe:x:39:39:John Doe:/var/lib/canna:/sbin/nologin' | cut -d ':' -f 7
chengpohi
  • 14,064
  • 1
  • 24
  • 42