29

I have a file named example

$ cat example

kali.pdf
linux.pdf
ubuntu.pdf
example.pdf.
this.pdf
grep .pdf

and when I use grep to get the line that has a space before .pdf, I can't seem to get it.

grep *.pdf example

returns nothing, (I want to say, "grep, match zero or more spaces before .pdf", but no result)

and if I use:

grep i*.pdf example

kali.pdf
linux.pdf
ubuntu.pdf
example.pdf.
this.pdf
grep .pdf

all lines return, because I'm saying "grep, match me i one or zero times, ok."

and lastly:

grep " *.pdf" example

no result returns

For this sample, I want to see

grep .pdf 

as output

What is wrong with my thought?

0

1 Answer 1

43

Make sure you quote your expression.

$ grep ' \.pdf' example
grep .pdf

Or if there might be multiple spaces (we can't use * as this will match the cases where there are no preceding spaces)

grep ' \+\.pdf' example

+ means "one or more of the preceding character". In BRE you need to escape it with \ to get this special function, but you can use ERE instead to avoid this

grep -E ' +\.pdf' example 

You can also use \s in grep to mean a space

grep '\s\+\.pdf' example

We should escape literal . because in regex . means any character, unless it's in a character class.

5
  • You were the first who noticed that the last line had space.
    – Pilot6
    Aug 24, 2017 at 7:36
  • @Pilot6 thanks. The question was a little confusingly written :)
    – Zanna
    Aug 24, 2017 at 7:38
  • 1
    There should be some badge for the first who understood the question ;-)
    – Pilot6
    Aug 24, 2017 at 8:11
  • @Zanna, is there anything wrong to go anytime egrep in this cases? egrep always gets you advantage...
    – solfish
    Aug 24, 2017 at 12:58
  • @solfish egrep is (in terms of regex style, afaik) the same as grep -E, and I believe we are meant to use the latter - egrep etc are supposedly deprecated in favour of grep's flags
    – Zanna
    Aug 24, 2017 at 13:37

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .