How to use regex match end of line in Windows
I have a .txt file created in Windows and now should be edited in Linux. I want to match the end of a line with grep. Let's say the content of the line I am going to find is "foo bar" in file bar
. Then I issue the command grep 'r$' bar
, but no output yielded.
Given in Windows a new line consists of '\r\n', diffe开发者_如何学Crent from Linux/Unix a single '\n', I think there must be something subtle related to this. Then I convert the file with dos2unix and voila, it works.
How can I match the content without convert the original file?
Use a pattern which matches both line ends: \r?\n
If your grep supports -P
(perl-regexp), then to match a CRLF:
grep -P '\r$' file
or:
grep Ctrl+VCtrl+M file
(Ctrl+VCtrl+M will produce ^M
)
Give it a try with AWK:
awk '/r$/' RS='\r\n' bar
or
awk '/r\r$/' bar
I had a similar issue in Windows Subsystem for Linux (WSL), running GNU Bash (v4.3.48) on Ubuntu. None of the suggestions above worked for me, but the following did (thanks to @phuclv for the tip to use \015
instead of Ctrl + V, Ctrl + M).
grep -Prno "TOKEN[^\015\012]*" *
I wanted to match from TOKEN
to the end of line and was getting back blanks. So I tried matching all the non carriage returns (\015
), and non newlines (\012
) after TOKEN
.
精彩评论