Search code examples
regexgrepcapture-group

grep capture regex


I am trying to use grep to capture data below:


"\\.xy$"
"\\.ab$"
"\\.ef\\.hi$"

I have

grep  -Eo "((\\\\\.[a-zA-Z]+)){1,2}\\$" file

two problems:

  1. It can capture things like \\.xy$, but not \\.xy\\.ef$
  2. the returned results have literal $ at the end, why?

Solution

  • Precede the dollar with a single backslash:

    % grep -Eo '"(\\\\\.[[:alpha:]]+){1,2}\$"' input
    "\\.xy$"
    "\\.ab$"
    "\\.ef\\.hi$"
    

    Or put the special characters into square brackets, which I find more readable:

    % grep -Eo '"([\]{2}[.][[:alpha:]]+)+"' input 
    "\\.xy$"
    "\\.ab$"
    "\\.ef\\.hi$"