【问题标题】:Extract pattern between a substring and first occurrence of numeric in a string提取子字符串和字符串中第一次出现的数字之间的模式
【发布时间】:2014-07-10 17:33:49
【问题描述】:

以下是文件的内容:

xxx_component1-1.0-2-2acd314.xc-linux-x86-64-Release-devel.r
xxx_component2-3.0-1-fg3sdhd.xc-linux-x86-64-Release-devel.r
xxx_component3-1.0-2-3gsjcgd.xc-linux-x86-64-Release-devel.r
xxx_component4-0.0-2-2acd314.xc-linux-x86-64-Release-devel.r

我想提取组件名称component1 component2等

这是我尝试过的:

for line in `sed -n -e '/^xxx-/p' $file`
do
    comp=`echo $line | sed  -e '/xxx-/,/[0-9]/p'`
    echo "comp - $comp"
done

我也试过sed -e 's/.*xxx-\(.*\)[^0-9].*/\1/'

这是基于网上的一些信息。请给我sed命令,如果可能的话也逐步解释

第 2 部分。我还需要从字符串中提取版本号。 版本号以 digit 开头,以 . 结尾。其次是xc-linux。 如您所见,为了保持唯一性,它具有随机字母数字字符(长度为 7)作为版本号的一部分。

例如: xxx_component1-1.0-2-2acd314.xc-linux-x86-64-Release-devel.r 在此字符串中,版本号为:1.0-2-2acd314

【问题讨论】:

    标签: sed matching substring


    【解决方案1】:

    有很多方法可以提取数据。最简单的形式是grep

    GNU grep:

    您可以使用带有 PCRE 选项 -P 的 GNU grep 获取所需的数据:

    $ cat file
    xxx_component1-1.0-2-2acd314.xc-linux-x86-64-Release-devel.r
    xxx_component2-3.0-1-fg3sdhd.xc-linux-x86-64-Release-devel.r
    xxx_component3-1.0-2-3gsjcgd.xc-linux-x86-64-Release-devel.r
    xxx_component4-0.0-2-2acd314.xc-linux-x86-64-Release-devel.r
    

    $ grep -oP '(?<=_)[^-]*' file
    component1
    component2
    component3
    component4
    

    在这里,我们在断言告诉后面使用否定查看来捕获从 _- 不包含在内的所有内容。


    awk:

    $ awk -F"[_-]" '{print $2}' file
    component1
    component2
    component3
    component4
    

    这里我们告诉awk 使用-_ 作为分隔符并打印第二列。


    sed:

    话虽如此,您也可以使用sed 使用组捕获来提取所需的数据:

    $ sed 's/.*_\([^-]*\)-.*/\1/' file
    component1
    component2
    component3
    component4
    

    正则表达式状态匹配任何字符零次或多次直到_。从那时起,捕获所有内容,直到组中的 -。在替换部分中,我们只是通过使用反向引用调用组中捕获的数据,即\1

    【讨论】:

    • 谢谢杰帕尔。我对你的 sed 做了一点修改,它似乎涵盖了所有用例:这就是我所做的: sed 's/xxx_([^-][^0-9]*)-.*/\1/'文件
    • 我再次来到这里,对相同的模式有另一个疑问。如果我想要模式的这一部分 1.0-2-2acd314(版本号)怎么办。按照上面的解释,这应该有效 sed s/*-[0-9].\(^.xc-*\)-.*/\1/'
    • @user3662599 如果您可以用所有可能的情况更新问题,那么我可以尝试提供一个适用于所有情况的通用解决方案。
    • 在来自字符串 xxx_component1-1.0-2-2acd314.xc-linux-x86-64-Release-devel.r 的原始问题中,我如何检索 1.0-2-2acd314 的版本号。
    猜你喜欢
    • 1970-01-01
    • 2017-08-20
    • 2022-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多