20

I'm trying to grep username:

users | grep "^\b\w*\b" -P

How can I get it to only show the first match with grep?

Eric Renouf
  • 18,141
  • 4
  • 49
  • 65
Yurij73
  • 1,922
  • 6
  • 20
  • 32
  • 3
    Why `grep`? `grep` is for searching. You seem to need either `cut` or `awk`, but the `read` builtin also seems suitable. – manatwork Dec 07 '12 at 12:20
  • this work as @peterph proposed ^\w*\b. Are cut or sed/awk more convinient? my case is simple. i can use myVar=\`users | grep -o "^\w*\b"\`, no? – Yurij73 Dec 07 '12 at 13:23
  • 3
    Compare them: `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)` or `read myVar blah <<< $(users)`. – manatwork Dec 07 '12 at 13:33
  • @Yurij73 the difference lies mostly in the execution time. with `read` you don't spawn a new process. If you do this many times, you'll notice the difference. – peterph Dec 07 '12 at 15:19
  • Does it better use awk? #!/bin/bash ( users|awk '$0=$1' )>file; read myVar – Yurij73 Dec 07 '12 at 20:03
  • Related: [How to get the first word of a string?](http://unix.stackexchange.com/q/65932/21471) – kenorb Oct 16 '15 at 15:23

4 Answers4

51

To show only the first match with grep, use -m parameter, e.g.:

grep -m1 pattern file

-m num, --max-count=num

Stop reading the file after num matches.

kenorb
  • 20,250
  • 14
  • 140
  • 164
10

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 read or cut/sed/awk seem to be more appropriate (particularly once you get to the point you'd need to do something more).

Stéphane Chazelas
  • 522,931
  • 91
  • 1,010
  • 1,501
peterph
  • 30,520
  • 2
  • 69
  • 75
2

it worked for me.the first match catch with:

users | grep -m 1 "^\b\w*\b"

and the last match catch with

users | grep "^\b\w*\b" |tail -1
Thomas
  • 6,242
  • 8
  • 26
  • 32
foad322
  • 21
  • 5
1

Why grep? The grep command is for searching. You seem to need either cut or awk, but the read builtin also seems suitable.

Compare them:

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)

or:

read myVar blah <<< $(users). 

Above answer based on @manatwork comments.

kenorb
  • 20,250
  • 14
  • 140
  • 164