Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use grep to search for words beginning with letter "s"

Tags:

linux

grep

I'm trying to use grep to look through a file, and find words starting with the lowercase letter "s". Snippet of the file:

sjpope   pts/2    161.133.12.95    10:21am 43.00s  0.13s  0.01s  man bc
rmschalk pts/3    161.133.9.147    10:22am  1.00s  0.10s  0.02s  vi testb
jntrudel pts/4    161.133.9.11     10:23am  2.00s  0.09s  0.00s  vi testb
tjbanks  pts/5    161.133.9.70     10:41am  8.00s  0.06s  0.04s  -ksh

I want the output to have line stating with "s".

like image 377
hurnhu Avatar asked Mar 19 '14 23:03

hurnhu


People also ask

How do I find a specific word with grep?

The easiest of the two commands is to use grep's -w option. This will find only lines that contain your target word as a complete word. Run the command "grep -w hub" against your target file and you will only see lines that contain the word "hub" as a complete word.

How do you grep with strings?

The basic grep syntax when searching multiple patterns in a file includes using the grep command followed by strings and the name of the file or its path. The patterns need to be enclosed using single quotes and separated by the pipe symbol. Use the backslash before pipe | for regular expressions.

How do you grep at the beginning of a line?

Use the ^ (caret) symbol to match expression at the start of a line. In the following example, the string kangaroo will match only if it occurs at the very beginning of a line. Use the $ (dollar) symbol to match expression at the end of a line.


1 Answers

For all these that want to search for words starting with given letter not for lines this one-liner will do:

grep -E '\bs' file.txt # all words starting with s
grep -E 's\b' file.txt # all words ending with s

I know that this is non standard grep behavior (\b regex anchor that means word break is not in extended regular expressions standard) but it works on most modern systems.

like image 125
csharpfolk Avatar answered Oct 18 '22 19:10

csharpfolk