Linux 如何在 Windows 中使用正则表达式匹配行尾?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6289286/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 04:25:03  来源:igfitidea点击:

How to use regex match end of line in Windows?

regexlinuxgrepnewline

提问by Summer_More_More_Tea

I have a .txt file created in Windows and now should be edited in Linux. I want to match end of a line with grep, let's say content of the line I gonna to find is "foo bar" in file bar. Then I issue the command grep 'r$' bar, no output yielded.

我有一个在 Windows 中创建的 .txt 文件,现在应该在 Linux 中进行编辑。我想用 grep 匹配行尾,假设我要找到的行的内容是 file 中的“foo bar” bar。然后我发出命令grep 'r$' bar,没有输出产生。

Given in Windows a new line consists of '\r\n', different from Linux/Unix a single '\n', I think there must be something subtle related to this. Then I convert the file with dos2unixand voila, it works.

鉴于 Windows 中的新行由 '\r\n' 组成,与 Linux/Unix 不同的是单个 '\n',我认为一定有一些微妙的与此相关。然后我用dos2unix和 voila转换文件,它的工作原理。

My question is how can I match the content without convert the original file?

我的问题是如何在不转换原始文件的情况下匹配内容?

Any advice will be highly appreciated.

任何建议将不胜感激。

Thanks and Best Regards.

谢谢和最好的问候。

采纳答案by dogbane

If your grep supports -P(perl-regexp), then to match a CRLF:

如果您的 grep 支持-P(perl-regexp),则要匹配 CRLF:

grep -P '\r$' file

or:

或者:

grep Ctrl+VCtrl+Mfile

grepCtrl+VCtrl+M文件

(Ctrl+VCtrl+Mwill produce ^M)

Ctrl+VCtrl+M会产生^M

回答by Aaron Digulla

Use a pattern with matches both line ends: r\r?\n

使用匹配行两端的模式: r\r?\n

回答by mug896

give it a try awk

试试 awk

awk '/r$/' RS='\r\n' bar

or

或者

awk '/r\r$/' bar

回答by ellemenno

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 tip to use \015instead of Ctrl+VCtrl+M).

我在 Windows Subsystem for Linux (WSL) 中遇到了类似的问题,在 Ubuntu 上运行 GNU bash (v4.3.48)。上面的建议都不适合我,但以下建议适用(感谢@phuclv 提示使用\015而不是Ctrl+VCtrl+M)。

grep -Prno "TOKEN[^52]*" *

I wanted to match from TOKENto end of line, and was getting back blanks. So I tried matching all the non carriage returns (\015), and non newlines (\012) after TOKEN.

我想从TOKEN行尾匹配,然后返回空白。所以我尝试匹配所有非回车符 ( \015) 和非换行符 ( \012) 之后TOKEN