Similar/Related to, but not covered by:
I mostly work in .NET stack, where we want (almost) all our files to be CRLF.
In my opinion, git should never be editing the contents of a file, so my and my projects' and my colleagues' git settings are autocrlf=false (i.e as-is, as-is), feel free to have that debate on some other question :)
Occasionally someone will have bad git settings, or in some other way accidentally introduce LFs into some files in the git repo, and I want to grep the whole repository for files with LF line-endings, and then fix them to be CRLFs, on a file-by-file basis (in case there are, e.g. bash files which should regrettably be LF).
Every time I need to do this, I can't find the relevant Regex and have to work it out from scratch again.
So this question exists to document the correct regex.
Regex to find any LF that is not part of a CRLF:
(?<!\r)\n
Regex to find any CR that is not part of a CRLF:
\r(?!\n)
Thus Regex to find any non-CRLF lineEnding:
((?<!\r)\n|\r(?!\n))
You can simply replace that with \r\n to fix them all to be CRLFs.
This is using the "Negative Lookbehind" functionality:
(?<\!a)bmatches a "b" that was not preceded by an "a".
and the "Negative Lookahead" functionality:
a(?\!b)matches an "a" that is not followed by a "b".
Further documentation here: https://www.regular-expressions.info/lookaround.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With