Ubuntu – grep pattern with leading spaces

bashgrepregex

I need some help in setting the correct pattern for grep. I need to find all occurrences of pattern where line may have leading space(s). For example: In the following file:

 1. No pattern recognized.
 2. Pattern to be recognized
 3.          Pattern to be recognized here also
 4.  pattern with only one leading space 

I would like to grep only lines 2,3 and 4. The line numbers are just for the reference.

So far I have tried the following:

grep -i '^ [[:blank:]]pattern', but it returns only line 4.

grep -i '[[:blank:]]pattern' returns 1,3 and 4.

grep -i '^[[:blank:]]pattern' returns 1,3 and 4.

— Mike
P.S.
If this is not the appropriate forum, then please guide me accordingly.

Best Answer

Your line 2 and 3 has upper case P and requires zero or more spaces, so specify exactly that:

$ grep '[[:blank:]]*Pattern'  input.txt                                  
 Pattern to be recognized
         Pattern to be recognized here also

Personally, I'd recommend extending your pattern with something else, like '[[:blank:]]Pattern.*recognized'