0

Suppose I've file with the following contents:

123
251
7.8
951

Now I want to grep the lines having . I've tried:

$ cat file | grep .
123
251
7.8
951

$ cat file | grep '.'
123
251
7.8
951

But it isn't working as expected. So, How do I grep string based on .?

Additional Info:

$ grep --version | line
grep (GNU grep) 2.16
  • @JeffSchaller This is not about Bash's behaviour of \ or \\ – Pandya Jan 31 '16 at 15:08
  • 1
    Agreed, but it's very much about the special behavior of ‘.', which that Q's answers cover. – Jeff Schaller Jan 31 '16 at 15:37
  • 1
    Escape the dot: grep '\.' file – Cyrus Jan 31 '16 at 20:48
8

That result you're getting is because . matches any single character

  • From manpage >REGULAR EXPRESSIONS:

       The fundamental building blocks are the regular expressions that match a single character. Most characters, including all letters and digits, are regular expressions that match themselves. Any meta-character with special meaning may be quoted by preceding it with a backslash.

       The period . matches any single character.

    So, . is required to be escaped with \

    $ cat file | grep '\.'
    7.8
    

    Note that here \. should be quoted with '.

  • Another way is to use -F, --fixed-strings option with grep or use fgrep.

     -F, --fixed-strings
              Interpret  PATTERN  as  a  list of fixed strings, separated by newlines, any of which is to be matched.
    

    Example:

    $ cat file | grep -F .
    7.8
    

    $ cat file | fgrep .
    7.8
    
  • Another work-around is to use bracket expression with enclosing a string which is to be matched inside [ and ]:

    $ cat file | grep '[.]'
    7.8
    

Not the answer you're looking for? Browse other questions tagged or ask your own question.