how to use grep to match with either whitespace or

2020-03-08 08:38发布

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..

标签: regex shell grep
3条回答
该账号已被封号
2楼-- · 2020-03-08 09:11

You can use the -e option of grep to select many patterns:

grep -e "AAA$" -e "AAA[[:space:]]"

From the grep man:

-e PATTERN, --regexp=PATTERN
      Use  PATTERN  as  the  pattern.   This  can  be  used to specify
      multiple search patterns, or to protect a pattern beginning with
      a hyphen (-).  (-e is specified by POSIX.)
查看更多
别忘想泡老子
3楼-- · 2020-03-08 09:20

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( |$)"
查看更多
祖国的老花朵
4楼-- · 2020-03-08 09:29

Use "AAA\b" if it's acceptable to also match AAA followed by any other non-alphanumeric character. According to the grep man pages, \b matches the empty string at the edge of a word.

$ echo -e "AAA VVV \nVVV AAA\nBBB" | grep "AAA\b"
AAA VVV
VVV AAA
查看更多
登录 后发表回答