How to include a space character with grep?
I have a file named example
$ cat example
kali.pdf
linux.pdf
ubuntu.pdf
example.pdf.
this.pdf
grep .pdfand when I use grep to get the line that has a space before .pdf, I can't seem to get it.
grep *.pdf examplereturns 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 .pdfall lines return, because I'm saying "grep, match me i one or zero times, ok."
and lastly:
grep " *.pdf" exampleno result returns
For this sample, I want to see
grep .pdf as output
What is wrong with my thought?
01 Answer
Make sure you quote your expression.
$ grep ' \.pdf' example
grep .pdfOr 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' exampleWe should escape literal . because in regex . means any character, unless it's in a character class.