Shell – Grep complete name including dot in the word

grepshell-scripttext processing

In a ksh shell script I am using a grep command to get a specific word as shown below.

$ cat file.txt
abc xyzdef.123 def.jkl mnopqrst

$ grep -o "\wdef\w" file.txt
xyzdef
def

I want output to be xyzdef.123 and def.jkl

It is not fetching the value after . Is there any other way to grep this word also I don't know the exact word to grep only I know a pattern. I am working on ksh shell.

Best Answer

Looks like you just want the string def and all non-whitespace characters around it. If so, you can use:

$ grep -Eo '\S*def\S*' file.txt 
xyzdef.123
def.jkl

The \S means non-whitespace and is supported by GNU grep with either the -E or -P flags.

Related Question