1. 7
  1.  

  2. 2

    I’ve been following this discussion on reddit/hn. As pointed out in those discussions, many of the issues in the post is due to shell, not specific to grep. Especially quoting. Always use single quotes to specify the search pattern, unless other forms of shell quoting is needed. Otherwise, you’ll face issues with commands like

    grep ; ip.txt
    grep # ip.txt
    

    Another example is searching for a pattern that starts with a hyphen, which causes issue even with quoting

    $ echo '5*3-2=13' | grep '-2'
    Usage: grep [OPTION]... PATTERN [FILE]...
    Try 'grep --help' for more information.
    

    You’ll need to either escape the hyphen or use -- before the search pattern to prevent it from being treated as a command option. This is needed if a filename starts with a hyphen too.

    I too have a list of grep gotchas and tricks here: https://learnbyexample.github.io/learn_gnugrep_ripgrep/gotchas-and-tricks.html

    1. 3

      As far as I can tell, exactly one issue (2) in the OP is due to shell. (1) and (4) are because of BRE/ERE syntax quirks. (3) is a typical regex mistake, not specific to grep or shell. And (5) is because you can’t build a POSIX compatible grep that searches UTF-16.

    2. 1

      The Most Confusing Shell Mistakes You’ve Ever Made.

      1. 1

        Hah, this is funny, just the other day I ran into a similar headscratcher, which I’ve written down here. It was fun to figure it out!

        1. 0

          TLDR: Shell quoting matters.