0

I'm trying to grab a word from a specific character for example if my sentence was

Hello, World!

and I wanted to search for e, my output would be

Hello,

I tried to user grep but had no luck, I also tried this

echo "Hello, World!" | grep -o e

output

e

is there any way I could get the output of "Hello,"

hrl
  • 5
  • 1

3 Answers3

2

Try following :

echo "Hello, World" | grep -o "\S*e\S*"

And also, if you want to remove all special characters in the string as "," etc, use following :

echo "Hello, World" | grep -o "\S*e\S*" | tr -dc '[:alnum:]\n\r'
Nishu Tayal
  • 20,106
  • 8
  • 49
  • 101
  • You can use `\S` instead of `[^[:space:]]` on GNU grep. – Tom Fenech Aug 27 '19 at 14:16
  • `\S` is generally not supported by `grep` (though some variants have it) but `[^[:space:]]` should work pretty much everywhere, as long as the platform is even vaguely POSIX. – tripleee Aug 28 '19 at 11:23
1

You can tell awk to treat each word as a record by setting the Record Separator RS to a space:

awk -v RS=' ' '/e/' <<<'Hello, World!'

On GNU awk, you can set RS to a regular expression to match one or more space characters, making things slightly more robust:

awk -v RS='\\s+' '/e/' <<<'Hello, World!'

The difference here is that multiple consecutive space characters will be treated as a single record separator. Additionally, other space characters (such as tabs) will be included.

Tom Fenech
  • 72,334
  • 12
  • 107
  • 141
1

Using Perl-compatible regular expressions with GNU grep:

echo 'Hello, World!' | grep -Po '\w*e\w*'

outputs:

Hello

The command literally means "output a word with an 'e' in it" (\w* means zero or more "word" characters).

For MacOS (from here):

echo 'Hello, World!' | perl -nle 'print $& while m{\w*e\w*}g'
Dennis Williamson
  • 346,391
  • 90
  • 374
  • 439