I got a file so something like:
helsoidfiejoih
heye heye hey
me is hi
The file can have any number of lines or characters in it the point is that it is a text file of some sort. Now the I need to use grep to do some operation so that the first parameter passed to grep is the filename and the second parameter is the pattern. But grep does a greedy match so it matches the whole line instead of a non greedy match which is what I want(non-greedy match). Now I tried:
grep -Ec -Po "$2" $1
It gives me conflicting expressions. And the user can enter any pattern A.K.A RE so the -E is a necessary option. Is there a way to make the grep non-greedy? I was told that the -P option makes the grep command non greedy but after trying out:
grep -c -Po "$2" $1
It does not seem to make the grep expression non greedy??
Edit: People said Im not showing the patterns I working with so to clarify the patterns will be a RE so for example if the user inputs in
./thisfile.sh h file1.txt
It will find the number of times h appears in file1.txt If the user inputs in
./thisfile.sh io file1.txt
It will find the number of times io appears in file1.txt. Is there a way to do this?
-E
and-P
enables extended regular expressions (ERE) and Perl-compatible regular expressions (PCRE), respectively. You cannot get both. This is what the error ("conflicting matchers specified") tells you. What do you want, PCRE or ERE? Also note that while-o
gives you one line per match, the-c
option will cancel the effect of-o
and only return the number of lines matched. It is unclear what your intention is with this. You also fail to quote$1
and your command fails if the pattern in$2
start with a dash. – Kusalananda Jun 11 '21 at 18:46-P
does not make your regular expressions non-greedy automatically. The-P
option enables Perl-compatible regular expressions (these are different from extended regular expressions enabled with-E
). These can be greedy or non-greedy, depending on how you write them. Ordinary regular expressions (with or without-E
) can probably be used too, but would have to be written to not match greedily across substrings that you don't actually want to match. – Kusalananda Jun 11 '21 at 20:10