2

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?
user775187
  • 18,341
  • 7
  • 26
  • 35

2 Answers2

2

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$"
hobs
  • 15,252
  • 8
  • 75
  • 93
Johnsyweb
  • 121,480
  • 23
  • 172
  • 229
  • almost works, I like the second approach, one problem: the $ still shows up in the results, but it's not part of the capture group, why? – user775187 Jun 13 '11 at 02:35
  • `-o` means "show only matching part of line", not the capture group `'(...)'`. What do you mean "almost works?" – Johnsyweb Jun 13 '11 at 02:48
  • @user775187: You can't with grep, but this will work: `grep '[$]"$' input | grep -Eo '"([\]{2}\.[[:alpha:]]+){1,2}'` – Johnsyweb Jun 13 '11 at 08:45
  • 1
    you can eliminate one more backslash in your readability version: `grep -Eo '"([\]{2}[.][[:alpha:]]+)+[$]"' input` – hobs Sep 25 '11 at 03:05
0

You've double-escaped the $ - try this:

grep  -Eo '"((\\\\\.[a-zA-Z]+)){1,2}\$"' file
Bohemian
  • 365,064
  • 84
  • 522
  • 658