【问题标题】:How to search and copy particular pattern from a file to another file如何搜索特定模式并将其从文件复制到另一个文件
【发布时间】:2014-01-13 14:09:53
【问题描述】:

我有一个这样的文件

MY-27125:some text
MY-27132:some text
MY-26565:some text
some text
MY-26097:some text
MY-27129:some text
MY-27211  && MY-26565:some text
some another text
MY-27175/MY-27147:some text
MY-27159\MY-27149:some text
MY-26747,MY-26945:some text
MY-20811 MY-26889:some text

我想使用 sed 或 notepad++ 或 awk 以仅包含以 MY-[5 位数字] 开头的文本。

输出应该如下所示

MY-27125
MY-27132
MY-26565
MY-26097
MY-27129
MY-27211
MY-27175
MY-27159
MY-26747
MY-20811
MY-26565
MY-27147
MY-27149
MY-26945
MY-26889

【问题讨论】:

  • 你有没有尝试过?有用吗?
  • 这很好用 grep -oP 'MY-\d{5}' 文件

标签: regex sed awk notepad++


【解决方案1】:

Grep 是正确的工具:

grep -oP 'MY-\d{5}' file

【讨论】:

    【解决方案2】:

    使用gnu awk

    awk 'NR>1 {print RS substr($0,1,5)}' RS="MY-" file
    MY-27125
    MY-27132
    MY-26565
    MY-26097
    MY-27129
    MY-27211
    MY-26565
    MY-27175
    MY-27147
    MY-27159
    MY-27149
    MY-26747
    MY-26945
    MY-20811
    MY-26889
    

    【讨论】:

      【解决方案3】:
      sed -n "/\(MY-[0-9]\{5\}\).*/ s//\1/p" YourFile
      

      在 GNU sed 上添加 -posix

      【讨论】:

        【解决方案4】:
        grep '^MY-' < in.txt | cut -b1-8 
        MY-27125
        MY-27132
        MY-26565
        MY-26097
        MY-27129
        MY-27211
        MY-27175
        MY-27159
        MY-26747
        MY-20811
        

        【讨论】:

        • 请注意,这不会在像MY-26747,MY-26945:some text 这样的行上打印第二个MY-
        猜你喜欢
        • 1970-01-01
        • 2016-08-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-02-24
        • 2013-06-25
        • 1970-01-01
        相关资源
        最近更新 更多