我想在 Linux 上使用 grep 搜索包含 DOS 行结尾的文件。 像这样的东西:
grep -IUr --color '\r\n' .
上面似乎与文字
rn
匹配,这不是我们想要的。
其输出将通过 xargs 传送到 todos,以将 crlf 转换为 lf,如下所示
grep -IUrl --color '^M' . | xargs -ifile fromdos 'file'
grep 可能不是您想要的工具。 它将为每个文件中的每个匹配行打印一行。 除非您想在 10 行文件上运行 todos 10 次,否则 grep 并不是最好的方法。 使用 find 在树中的每个文件上运行 file,然后通过 grep 查找“CRLF”将为每个具有 dos 样式行结尾的文件提供一行输出:
find . -not -type d -exec file "{}" ";" | grep CRLF
会给你一些类似的东西:
./1/dos1.txt: ASCII text, with CRLF line terminators
./2/dos2.txt: ASCII text, with CRLF line terminators
./dos.txt: ASCII text, with CRLF line terminators
使用 Ctrl+V、Ctrl+M 在 grep 字符串中输入回车符。所以:
grep -IUr --color "^M"
会起作用 - 如果
^M
有一个文字 CR,您按照我的建议输入。
如果您想要文件列表,您还需要添加
-l
选项。
解释
-I
忽略二进制文件-U
防止 grep 剥离 CR 字符。默认情况下,如果它确定它是一个文本文件,它就会执行此操作。-r
递归读取每个目录下的所有文件。使用 RipGrep(根据您的 shell,您可能需要引用最后一个参数):
rg -l '\r'
-l, --files-with-matches
Only print the paths with at least one match.
如果您的 grep 版本支持 -P (--perl-regexp) 选项,则
grep -lUP '\r$'
可以用。
# list files containing dos line endings (CRLF)
cr="$(printf "\r")" # alternative to ctrl-V ctrl-M
grep -Ilsr "${cr}$" .
grep -Ilsr $'\r$' . # yet another & even shorter alternative
dos2unix
有一个文件信息选项,可用于显示要转换的文件:
dos2unix -ic /path/to/file
要递归地执行此操作,您可以使用
bash
的 globstar
选项,该选项对于当前 shell 是通过 shopt -s globstar
启用的:
dos2unix -ic ** # all files recursively
dos2unix -ic **/file # files called “file” recursively
您也可以使用
find
来实现:
find -type f -exec dos2unix -ic {} + # all files recursively (ignoring directories)
find -name file -exec dos2unix -ic {} + # files called “file” recursively
您可以在unix中使用文件命令。它为您提供文件的字符编码以及行终止符。
$ file myfile
myfile: ISO-8859 text, with CRLF line terminators
$ file myfile | grep -ow CRLF
CRLF
查询是搜索...我有类似的问题...有人提交了混合行 版本控制中的结尾,所以现在我们有一堆带有
0x0d
的文件
0x0d
0x0a
行结尾。请注意
grep -P '\x0d\x0a'
查找所有行,而
grep -P '\x0d\x0d\x0a'
和
grep -P '\x0d\x0d'
找不到任何行,因此 grep 内部可能发生了“其他”事情 当谈到行结束模式时......对我来说不幸的是!
如果像我一样,您的极简主义 Unix 不包含 file 命令之类的细节,并且 grep 表达式中的反斜杠不配合,请尝试以下操作:
$ for file in `find . -type f` ; do
> dump $file | cut -c9-50 | egrep -m1 -q ' 0d| 0d'
> if [ $? -eq 0 ] ; then echo $file ; fi
> done
您可能想要对上述内容进行的修改包括:
例如,使用 od 而不是 dump:
类似的操作可能对您有用 od -t x2 -N 1000 $file | cut -c8- | egrep -m1 -q ' 0d| 0d|0d$'