grep case sensitive [A-Z]?

2019-06-15 00:53发布

问题:

I cannot get grep to case sensitive search with this pattern

$ grep 'T[A-Z]' test.txt
The Quick Brown Fox Jumps Over The Lazy Dog
THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG

回答1:

Use quotes to prevent the pattern from being matched as a glob to file(s) in the filesystem by the shell. ''

Use a named character class to guarantee a case-sensitive match. [[:lower:]]

Use a quantifier to make matches for more than one character. \+

Use anchor(s) to make sure the match is positioned properly. ^

grep '^T[[:upper:]]\+' test.txt

The reason that [A-Z] isn't working for you is that the way the locale you're using is implemented on your system, that pattern also includes lowercase letters.



回答2:

You can set LANG value:

$ LANG=C grep 'T[A-Z]' test.txt
THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG


回答3:

grep 'T[[:upper:]]' test.txt
grep 'T[ABCDEFGHIJKLMNOPQRSTUVWXYZ]' test.txt