I'm trying to grep username:
users | grep "^\b\w*\b" -P
How can I get it to only show the first match with
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It only takes a minute to sign up.Sign up to join this community
If you really want return just the first word and want to do this with
grep and your
grep happens to be a recent version of GNU
grep, you probably want the
-o option. I believe you can do this without the
-P and the
\b at the beginning is not really necessary. Hence:
users | grep -o "^\w*\b".
Yet, as @manatwork mentioned, shell built-in
awk seem to be more appropriate (particularly once you get to the point you'd need to do something more).
grep command is for searching. You seem to need either
awk, but the read builtin also seems suitable.
users | cut -d' ' -f1 users | sed 's/\s.*//' users | awk '$0=$1'
If you want to store it in a variable, using bash:
read myVar blah < <(users)
read myVar blah <<< $(users).
Above answer based on @manatwork comments.