bash 以数字结尾的 Grep 行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47486799/
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
Grep lines that end with numbers
提问by David Halliday
I have a list of lines like:
我有一个像这样的行列表:
Spend: 4,100
Spend2: 2,200
Spend3: 300
Spend4: 1,590
Spend5:
and I'm trying to grep
just the lines that end with numbers
我试图grep
只以数字结尾的行
I tried
我试过
grep "[0-9]+$" filename.txt > filtered.txt
grep "\d$" filename.txt > filtered.txt
but none of these worked
但这些都没有用
回答by tripleee
The +
operator is not supported by traditional grep
, whose regular expression reperttheitroade is very limited.
+
传统 不支持该运算符grep
,其正则表达式库非常有限。
All you really care about is whether the last character is a digit, so
你真正关心的是最后一个字符是否是数字,所以
grep '[0-9]$' filename.txt
should do what you want. Other approaches include
应该做你想做的。其他方法包括
grep -E '[0-9]+$' filename.txt # use extended regex reperttheitroade
grep '[0-9]\+$' filename.txt # POSIX BRE extended
grep -P '\d+$' filename.txt # PCRE extended; not portable
Notice how I use single quotes throughout. Double quotes introduce additional complications especially with backslashes which you probably want to avoid.
请注意我如何在整个过程中使用单引号。双引号引入了额外的复杂性,尤其是您可能想要避免的反斜杠。
回答by RomanPerekhrest
On Basic regular expressionsmode you should specify the pattern in the following way:
在基本正则表达式模式下,您应该按以下方式指定模式:
grep '[0-9]\+$' filename.txt > filtered.txt
In basic regular expressions the meta-characters ‘
?
', ‘+
', ‘{
', ‘|
', ‘(
', and ‘)
' lose their special meaning; instead use the backslashed versions ‘\?
', ‘\+
', ‘\{
', ‘\|
', ‘\(
', and ‘\)
'.
在基本的正则表达式中,元字符 '
?
'、'+
'、'{
'、'|
'、'(
' 和 ')
' 失去了它们的特殊意义;而是使用反斜杠版本“\?
”、“\+
”、“\{
”、“\|
”、“\(
”和“\)
”。
回答by Pilgrim
For extended regular expressions you should use egrep
or grep -E
.
对于扩展的正则表达式,您应该使用egrep
或grep -E
。