6

I'm trying to grep all line breaks after some binary operators in a project using git bash on a Windows machine.

Tried the following commands which did not work:

$ git grep "[+-*\|%]\ *\n"
fatal: command line, '[+-*\|%]\ *\n': Invalid range end

$ git grep "[+\-*\|%]\ *\n"
fatal: command line, '[+\-*\|%]\ *\n': Invalid range end

OK, I don't know how to include "-" in a character set, but still after removing it the \n matches the character n literally:

$ git grep "[+*%] *\n"
somefile.py:            self[:] = '|' + name + '='
                                      ^^^

Escaping the backslash once (\\n) has no effect, and escaping it twice (\\\n) causes the regex to match \n (literally).

What is the correct way to grep here?

jbu
  • 15,831
  • 29
  • 82
  • 105
AXO
  • 8,198
  • 6
  • 62
  • 63

2 Answers2

6

I don't know how to include "-" in a character set

There is no need to escape the dash character (-) if you want to include it in a character set. If you put it the first or the last character in set it doesn't have its special meaning.

Also, there is no need to escape | inside a character range. Apart from ^ (when it's the first character in the range), - (when it is not the first or the last character in the range), ] and \ (when it is used to escape ]), all other characters have their literal meaning (i.e no special meaning) in a character range.

There is also no need to put \n in the regexp. The grepping tools, by default, try to match the regexp against one row at a time and git grep does the same. If you need to match the regexp only at the end of line then put $ (the end of line anchor) as the last character of the regexp.

Your regexp should be [-+*|%] *$.

Put together, the complete command line is:

git grep '[-+*|%] *$'
axiac
  • 68,258
  • 9
  • 99
  • 134
  • Thanks! I had to use `grep '[-+*|%]\s*$'` to account for windows line endings. It turns out that I could also find the answer in [grep manual](https://www.gnu.org/software/grep/manual/grep.html#Character-Classes-and-Bracket-Expressions). See also: [Is it better to use git grep than plain grep if we want to search in versioned source code?](http://stackoverflow.com/questions/17557684/is-it-better-to-use-git-grep-than-plain-grep-if-we-want-to-search-in-versioned-s) – AXO Jan 21 '17 at 12:25
0

How to find a newline in the middle of a line

For lack of better option I think I'll start with:

sudo apt install pcregrep
git grep --cached -Il '' | xargs pcregrep -Mb 'y\nl'

this combines:

The output clearly shows the filename and line number, e.g.:

myfile.txt:123:my
love
myfile.txt:234:my
life
otherfile.txt:11:my
lion

Tested on Ubuntu 22.04.

Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985