You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用egrep匹配连续5位或9位数字的问题求助

Fixing Your egrep Pattern for Matching 5 or 9-Digit Numbers

Let me walk you through fixing this egrep issue. The problem with your current command is two-fold:

  • You’re using line anchors (^ for start of line, $ for end of line), which limit matches to only digits at the very start or end of a line.
  • The spaces in your regex (^[[:digit:]]{5} and [[:digit:]]{9}$) force matches to be followed or preceded by a space, so you’re missing valid digits that are surrounded by other characters or in the middle of the line without adjacent spaces.

The Correct Command

To find all 5-digit or 9-digit numbers anywhere in each line, use this command:

egrep -o '[[:digit:]]{5}|[[:digit:]]{9}' file.txt

What this does:

  • The -o flag tells egrep to output only the matched parts of the line, instead of the entire line.
  • [[:digit:]]{5} matches any sequence of exactly 5 digits.
  • | acts as an OR operator, so we also match [[:digit:]]{9} (exactly 9 digits).
  • No anchors or extra spaces mean the regex will find these digit sequences anywhere in the line.

Testing with Your Example

For your file.txt content:

123456789 24 12345 642 94363

Running the command will output:

123456789
12345
94363

Bonus: Avoid Partial Matches in Longer Numbers

If you want to ensure you’re matching whole numbers (not, say, the first 5 digits of a 6-digit number like 123456), add word boundaries (\< and \>) to the regex:

egrep -o '\<[[:digit:]]{5}\>|\<[[:digit:]]{9}\>' file.txt

This ensures the digits are surrounded by non-word characters (like spaces, start/end of line, punctuation) so you don’t get partial matches from longer digit sequences.

内容的提问来源于stack exchange,提问作者John Shin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:29:21