Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use grep to match with either whitespace or newline

Tags:

regex

grep

shell

I want to grep a file with a word, say "AAA", and it ends with whitespace or newlines. I know how to write this seperately, as follows, but having problems in combining them (in the sense that it outputs both VVV AAA and AAA VVV).

$echo -e "AAA VVV \nVVV AAA\nBBB" | grep "AAA$" 
>VVV AAA
$echo -e "AAA VVV \nVVV AAA\nBBB" | grep "AAA[[:space:]]" 
>AAA VVV 

I have tried using [], but without success..

like image 659
Richard Avatar asked Nov 04 '12 15:11

Richard


People also ask

Can you use regex with grep?

GNU grep supports three regular expression syntaxes, Basic, Extended, and Perl-compatible. In its simplest form, when no regular expression type is given, grep interpret search patterns as basic regular expressions. To interpret the pattern as an extended regular expression, use the -E ( or --extended-regexp ) option.

Can you use wildcards with grep?

The wildcard * (asterisk) can be a substitute for any number of letters, numbers, or characters. Note that the asterisk (*) works differently in grep. In grep the asterisk only matches multiples of the preceding character. The wildcard * can be a substitute for any number of letters, numbers, or characters.


1 Answers

If you are looking for word AAA followed by space anywhere in the string, or at the end of line, then use

grep -P "AAA( |$)"
like image 119
Ωmega Avatar answered Sep 28 '22 07:09

Ωmega