Sami
Sami

Reputation: 305

How to grep only the first string in a line

I'm writing a script that checks a list of all the users connected to the server (using who) and writes to the file Information the list of usernames of only those having letters a, b, c or d. This is what I have so far:

 who | grep '[a-d]' >> Information

However, the command who displays this:

username pts/148      2019-01-29 16:09 (IP address)

What I don't understand is why my grep search is also displaying the pts/148, date, time, and IP address. I just want it to send the username to the file Information.

Any help is appreciated.

Upvotes: 1

Views: 6664

Answers (3)

James Brown
James Brown

Reputation: 37464

Using awk to output records where the first clumn matches [a-d]:

$ who | awk '$1~/[a-d]/' >> Information

Using grep to search for lines with [a-d] before the first space:

$ who | grep -o "^[^ ]*[a-d][^ ]*" >> Information

Upvotes: 1

Ass3mbler
Ass3mbler

Reputation: 3935

Another way is to use the command cut to get the first part of the string only.

who | cut -f 1 -d ' ' | grep '[a-d]' >> Information

Upvotes: 5

P.P
P.P

Reputation: 121427

You need to get the first word, otherwise grep will display the entire line that has the matching text. You could use awk:

who | awk '{ if (substr($1,1,1) ~ /^[a-d]/ ) print $1 }' >>Information

Upvotes: 0

Related Questions