为什么 grep 输出的行看起来与表达式不匹配?

为什么 grep 输出的行看起来与表达式不匹配?

为什么 grep 输出的行看起来与表达式不匹配?

正如中提到的我的评论此行为可能是由错误引起的。

我知道不同的语言环境会影响字符顺序,但我认为下面的 -o 输出确认这不是问题,但我错了。添加 LC_ALL=C 会给出预期的输出。

我有这个问题在我看到语言环境影响输出之后。

[aa@bb grep-test]$ cat input.txt
aa bb
CC cc
dd ee

[aa@bb grep-test]$ LC_ALL=C grep -o [A-Z] input.txt
C
C
[aa@bb grep-test]$ grep -o [A-Z] input.txt
C
C
[aa@bb grep-test]$ LC_ALL=C grep [A-Z] input.txt
CC cc
[aa@bb grep-test]$ grep [A-Z] input.txt
aa bb
CC cc
dd ee
[aa@bb grep-test]$





[aa@bb tmp]$ cat test
aa bb
CC cc
dd ee

[aa@bb tmp]$ grep [A-Z] test
aa bb
CC cc
dd ee
[aa@bb tmp]$ grep -o [A-Z] test
C
C
[aa@bb tmp]$ grep -E [A-Z] test
aa bb
CC cc
dd ee
[aa@bb tmp]$ grep -n [A-Z] test
1:aa bb
2:CC cc
3:dd ee
[aa@bb tmp]$ echo [A-Z]
[A-Z]
[aa@bb tmp]$ grep -V
GNU grep 2.6.3
...
[aa@bb tmp]$ bash --version
GNU bash, version 4.1.2(1)-release (x86_64-redhat-linux-gnu)
...
[aa@bb grep-test]$ command -v grep
/bin/grep
[aa@bb grep-test]$ rpm -q -f $(command -v grep)
grep-2.6.3-6.el6.x86_64
[aa@bb grep-test]$ echo grep [A-Z] input.txt | xxd
0000000: 6772 6570 205b 412d 5a5d 2069 6e70 7574  grep [A-Z] input
0000010: 2e74 7874 0a                             .txt.    
[aa@bb grep-test]$ cmd='grep [A-Z] input.txt'; echo $cmd | xxd; eval $cmd
0000000: 6772 6570 205b 412d 5a5d 2069 6e70 7574  grep [A-Z] input
0000010: 2e74 7874 0a                             .txt.
aa bb
CC cc
dd ee
[aa@bb grep-test]$ xxd input.txt
0000000: 6161 2062 620a 4343 2063 630a 6464 2065  aa bb.CC cc.dd e
0000010: 650a 0a                                  e..
[aa@bb grep-test]$

答案1

你的“A”不是拉丁语“A”:

cmd='grep [A-Z] test'; echo $cmd | xxd; eval $cmd
0000000: 6772 6570 205b ***41***2d 5a5d 2074 6573 740a  grep [A-Z] test.
CC cc


cmd='grep [А-Z] test'; echo $cmd | xxd; eval $cmd
0000000: 6772 6570 205b ***d090*** 2d5a 5d20 7465 7374  grep [..-Z] test
0000010: 0a                                       .
aa bb
CC cc
dd ee

答案2

这看起来你的区域设置排序规则非常......有帮助。

尝试一下

LC_ALL=C grep [A-Z] input.txt

来测试这个想法。

我有

export LANG=en_US.UTF-8
export LC_COLLATE=C
export LC_NUMERIC=C

在我的 shell 启动中以避免这种麻烦,同时仍然获得我的 unicode 优点。

答案3

无法使用 BSD 或 GNU 进行复制grep

BSD:

$ cat test
aa bb
CC cc
dd ee
$ grep [A-Z] test
CC cc
$ grep --version
grep (BSD grep) 2.5.1-FreeBSD

GNU:

$ cat test
aa bb
CC cc
dd ee
$ grep [A-Z] test
CC cc
$ grep --version
grep (GNU grep) 2.25
Copyright (C) 2016 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>.
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

Written by Mike Haertel and others, see <http://git.sv.gnu.org/cgit/grep.git/tree/AUTHORS>.

相关内容