【问题标题】:regular expression for matching number匹配号码的正则表达式
【发布时间】:2012-12-31 10:21:32
【问题描述】:

我有一个文件调用 phonenum.txt,其中包含已通过 procmail 配方从文件中过滤的电话号码列表:

60123456098,60135673434,60149023459,60123456334

根据此文件,需要满足两个条件才能获得它们的输出。

  1. 输出必须通过数字 60(它是国家代码,所以它是我可以在所有数字之间使用的唯一常量)和这些数字前面的“,”符号来区分。例如:60135673434..
  2. 如果60在电话号码中间怎么办?例如:60123456098如何获得整数的输出?

无论如何,我可以通过在 awk 或 sed 中使用匹配正则表达式来获取电话号码吗?

【问题讨论】:

  • 如果字符串只包含这些电话号码,为什么不简单地用逗号分割呢?

标签: regex linux unix sed awk


【解决方案1】:
awk -F, '{for(i=1;i<=NF;i++)if($i~/^60/){print "phone number is ",substr($i,3)}}' your_file

测试如下:

> cat temp
60123456098,60135673434,60149023459,60123456334,90123456789
> nawk -F, '{for(i=1;i<=NF;i++)if($i~/^60/){print "phone number is ",substr($i,3)}}' temp
phone number is  123456098
phone number is  135673434
phone number is  149023459
phone number is  123456334
>

【讨论】:

    【解决方案2】:

    你可以的

    awk -v RS="," '{gsub(/^60/,"")} 1' file
    

    如果你想回一行

    awk -v RS="," '{gsub(/^60/,"")} {printf s $0; s=","}' file
    

    【讨论】:

      【解决方案3】:
      $ grep -oP '(?<=\b60)\d+' <<< "60123456098,60135673434,60149023459,60123456334"
      123456098
      135673434
      149023459
      123456334
      

      【讨论】:

        【解决方案4】:

        如何用sed 使用(^|,)60 进行全局替换:

        $ sed -r 's/(^|,)60/\1/g' <<< 60123456098,60135673434,60149023459,60123456334 
        123456098,135673434,149023459,123456334
        

        正则解释:

        s/          # Substitution 
        (^|,)       # Match start of the line or comma (captured)
        60          # Followed by the literal 60 
        /           # Replace with
        \1          # Captured group (put back the comma) 
        /g          # Global flag
        

        【讨论】:

          【解决方案5】:

          这可能对你有用(GNU sed):

          sed 's/^60//;s/,60/\n/g;P;D' file
          

          【讨论】:

            猜你喜欢
            • 2010-12-16
            • 1970-01-01
            • 2020-01-18
            • 2021-07-31
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2012-01-11
            • 2011-08-03
            相关资源
            最近更新 更多