Find characters in a string surrounded by spaces in bash using egrep

I have a file that looks like this:

Arjun
A
   A
 A
sdsdA
AA
AAA

      

I want to find lines that contain A that is surrounded by white space on both sides. The intended output for this would be:

   A
 A

      

Only lines 3 and 4 should appear in the output. I've tried the following:

egrep '(^|\s)A($|\s)' filename

      

and got this in the output:

A
   A
 A

      

It somehow matches the second line, which starts with a single A. How do I avoid this?

+3


source to share


2 answers


Assuming you have actual space on either side of the 2nd and 3rd lines "A" and not ending with A, then either one should work with grep or egrep, matching only space, character A, space

grep " A " filename
grep ' A ' filename

      

Or using a character class:

grep '[[:space:]]A[[:space:]]' filename

      



But the class [[:space:]]

can also match all "whitespace" (tab, newline , vertical tab, form feed, carriage return and space) according to the GNU.org grep manual , but it doesn't match newline for mine grep (GNU grep) 2.16

unless A, but the end line is not a newline.

Apparently GNU.org tells me that ā€˜\sā€™

Matches a space, it is a synonym[[:space:]]

So, this s [[:blank:]]

should only match a space or tab:

grep '[[:blank:]]A[[:blank:]]' filename

      

+4


source


Since you don't want to A

start or end, you don't need ^

both $

:



~$ egrep '\sA\s' filename
   A  
 A  

      

+2


source







All Articles