I need to find a user for a userid. The return from the authentication system is as follows. Now with a bash script I need to extract the line with the exact number. Not 5 and 25 ..

28  user1
25  user2 
5   user3

If I use grep 5 I do get 2 lines but I need the line with "5".

Any ideas ?


There are several ways of doing it.

IMHO the best way is to use awk, which is useful when dealing with fields.

If you want a grep based solution, I would do:

grep -w '^5'

The -w tells grep to match the exact word, so this will not match "52". The "^" tells grep to search the 5 at the beginning of the line, which will fail if there are e.g. leading spaces.

The awk solution would look like:

awk '$1 == 5'

If you want only the username, which is the second column:

awk '$1 == 5 {print $2}'

If you're searching for a string and not a numeric value, enclose the string in double quotes:

awk '$1 == "abc" {print $2}'
  • 1
    thanks I have choosen the awk way. awk '$1 == 5 {print $2}' that worked. – Dave. Jan 9 at 14:05
  • 2
    @Dave. Since this answer worked for you, please consider clicking the checkbox beside it to signal to future readers it answered your question. – bishop Jan 9 at 20:59

You could try with a regex (first char in line) and including the space:

grep -E "^5 "
  • 4
    This would be better as grep -E "^5\s" in case there's a tab and not a space. – terdon Jan 9 at 13:50

Try the following:

query-auth-system | grep "^5\\>"
  • ^: means "match at start of line
  • \\>: matches a word-boundary. So it will match 5, but not 50.
  • 2
    That will also match lines starting with 5:, 5%, 5| etc. – terdon Jan 9 at 13:49

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.