windows - 如何让 grep 忽略 Windows 换行符?

标签 windows bash grep line-endings

在 Mac OS X 上,我有一个带有 Windows 换行符和以下内容的文件

$ file file_windows.txt 
file_windows.txt: ASCII text, with CRLF line terminators
$ cat file_windows.txt
IgnoreMe
FindMe

奇怪的是,当我使用 grep 匹配“FindMe”并将结果与​​另一个变量组合时,grep 的结果被忽略:

$ echo $(grep "FindMe" file_windows.txt)$SHELL
/bin/bash

当我将文件转换为使用 unix 行结尾时

tr -d '\r' < file_windows.txt > file_unix.txt 

然后我的 grep 命令突然与另一个变量结合使用

$ echo $(grep "FindMe" file_unix.txt)$SHELL
FindMe/bin/bash

如何使 grep 忽略(windows)换行符,以便将 grep 的结果与另一个变量相结合的以下命令始终按预期工作?

最佳答案

当你运行时:

$ echo $(grep "FindMe" file_windows.txt)$SHELL

echo 将打印包含 FindMe 的行,该行又包含\r 字符,以便 $SHELL 将覆盖 FindMe\r。您可以通过将 echo 重定向到文件来轻松检查这一点。

要解决此问题,您可以要求 grep 以“零字节”终止匹配字符串,如下所示:

$ echo $(grep -Z "FindMe" file_windows.txt)$SHELL 

编辑

我确实注意到您正在使用 OSX。在这种情况下,请使用以下内容:

$ echo $(grep -o "FindMe" file_windows.txt)$SHELL

仅打印“匹配字符串”

关于windows - 如何让 grep 忽略 Windows 换行符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35604030/

相关文章:

python - 为 Python 脚本存储 Windows 配置文件的好地方/方法在哪里?

linux - awk、pipe 和 tail -f 给出意外行为

linux - 在 Linux 中从文件中删除行,完全匹配

regex - 在perl中对文本 block 进行排序

c# - 在 C# 中找出谁锁定了网络驱动器上的文件

windows - 当不知道 InterfaceClassGUID 时,我可以使用 SetupDiEnumDeviceInterfaces 从 SetupDiGetDeviceInterfaceDetail 获取 DevicePath 吗?

php - 为什么从 CRON 运行 php 脚本会导致字符编码问题?

linux - 如何使用bash删除txt文件开头的字符?

command-line - 使用 Silver Searcher 搜索文件和文件名

windows - 从 Windows 机器 SSH 到 Kubernetes 主节点