0

Maybe I'm missing something very simple, but I don't seem to be able to use grep from the command line (in bash) where the search argument contains a vertical bar |.
For example,

grep a|b

results in the error bash: b: command not found. Of course.
Escaping the pipe

grep a\|b

gets rid of the error, but results in grep itself interpreting the pipe as a literal search character (i.e. it searches for the text a|b in the input rather than "a or b").

grep "a|b"

has the same result: it also searches for the literal text a|b.

So, what now? I also tried ' and ` for delimiters, and now I'm out of things to think of.
Open to suggestions!

(In case it matters, this is with Debian 12, KDE and konsole for a terminal.)

2
  • What are you trying to do exactly? This question has an excellent answer which explains the reason what you have tried does not work. It comes down to the fact | isn’t a special character in the eyes of grep
    – Ramhound
    Commented May 26 at 15:48
  • Thanks. I did search, but I missed that one for some reason.
    – Mr Lister
    Commented May 26 at 16:27

1 Answer 1

2

gets rid of the error, but results in grep itself interpreting the pipe as a literal search character (i.e. it searches for the text a|b in the input rather than "a or b").

It has no effect on grep interpreting the pipe (the kind of quoting you used is invisible to grep; it only receives the string a|b either way) – grep always interprets pipe as a literal character.

Grep uses POSIX 'basic' regular expressions, which don't have this functionality at all (although some implementations add it using \|).

Use grep -E or egrep to activate the "POSIX extended" regular expression language where | actually means what you expect it to mean, or grep -P to activate support for PCRE (Perl-like) regular expressions.

2
  • 2
    although some implementations add it using \| In that case grep 'a\|b' (or grep a\\\|b) should work?
    – Tom Yan
    Commented May 26 at 15:52
  • Thanks. I was confused what the default type of RE was. grep --help mentions -E, -F, -G and -P but it doesn't say which one is the default.
    – Mr Lister
    Commented May 26 at 16:48

You must log in to answer this question.

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