Reputation: 338
Actual answer to my question might be very simple(probably I just have to read the reg-ex tutorials again). But this is more on the behavior which I saw with grep and '-' character.
I've a patch file(diff.txt) which contains entries like.
--- a/path/to/xyz
+++ b/path/to/modified/xyz
Now, for some reason I wanted to grep all lines in the file which exactly contains "---" pattern.
After simple grep commands failed to give me what I wanted, I tried below three commands:
$ grep "-" ./diff.txt
The above one yields the results showing all the existence of '-' symbol(single occurence, multiple occurence ).
$ grep "--" ./diff.txt
This one yields nothing. No output. Grep got stuck in some loop?(trying to find out something which is not there?). Had to Ctrl-C to stop the command.
$ grep "---" ./diff.txt
After this one, Grep complains of Unrecognized pattern and prints the help message.
In case, someone is wondering, I did try the same command with a "+++" pattern and a simple grep command worked like a charm:
$ grep "+++" ./diff.txt --> output all the lines correctly.
I'll appreciate if someone could explain this strange behavior with '-' character.
Upvotes: 0
Views: 174
Reputation: 15501
Since your pattern starts with a dash it's being interpretted as an option. Either explicitly indicate the end of options with the --
option, or explicitly indicate that your pattern is a pattern with the -e
option.
$ echo -e "---abc\ndef\n---ghi\njkl"
---abc
def
---ghi
jkl
$ echo -e "---abc\ndef\n---ghi\njkl" | grep -- ---
---abc
---ghi
$ echo -e "---abc\ndef\n---ghi\njkl" | grep -e ---
---abc
---ghi
(The -e
option to the echo
command allows c-style escapes like \n
.)
Upvotes: 1
Reputation: 99921
A pattern starting with a -
is interpreted as an option.
--
means end of options.
Use --
to tell grep that any following arguments are not options.
grep -- pattern path...
Upvotes: 3
Reputation: 75498
Grep may be trying to interpret your pattern as an option.
Use -e
to make it explicit:
grep -e --- ./diff.txt
Upvotes: 3