爲了在僅含有一個單一的數字文件的grep線,並且只有一個單一的數字
執行此
grep -P '^\D*\d\D*$' file
-P標誌是使Perl表達式
http://www.gnu.org/software/grep/manual/grep.html
該表達式本身是一個正則表達式
'^\D*\d\D*$'
'^' = 'start of a line'
'\D*' = '0 or more non-digits'
'\d' = '1 digit'
'\D*' = '0 or more non-digits'
'$' = 'End of line'
更新:
即使問題得到解答和接受,這種解決方案可以幫助別人誰碰到這個問題。正如TomZych在評論中提到P是實驗性的,所以我將它與E切換,這是--extended-expression。
標題改變後,我以前的答案不是OP想要的。 因此,這裏是新的表達式:
grep -E '^([^0-9]|[0-9]{2,})*([0-9][^0-9]*)([^0-9]|[0-9]{2,})*$' file
表達解釋
'^' # start of line
我們先從第一組。
([^0-9]|[0-9]{2,})* # The first group:
'(...)' # what ever is inside the parantheses is in the group.
'*' # means repeat this expression zero or more times.
'[^0-9]', '[0-9]' # means all digits from 0-9, but the
'^' # means NOT when its in the squared brackets.
'{2,}' # means this expression 2 or more times
'|' # means OR
# So what we want here is:
# Zero or more, (non-digits characters or two or more digits numbers)
# This will match anything untill we meet a single digit number.
然後是第二組。
([0-9][^0-9]*) # second group:
# Here we want to match a single digit
'[0-9]'
# Followed by zero or more non-digits
'[^0-9]'
# This will match the single digit, the first group ran into.
# I use zero or more incase its the end of the line.
然後3.組至極實際上是再次第一組中,零次或多次。
# Followed by
'$' # End of line
這將匹配任何行,其中僅存在一個單個數字。
1 abc 123
abc 1 123
abc 123 1
abc 1 abc
123 1 123
abc1abc
# will all match
你試圖得到什麼結果? – EL3PHANTEN