【问题标题】:extract text between 2 strings only till first occurence of end string仅在第一次出现结束字符串之前提取 2 个字符串之间的文本
【发布时间】:2014-11-28 21:30:33
【问题描述】:

我正在尝试在 device_uuid: 和立即数之间提取字符串,

d

device_uuid:xxx,yyy,ttt
device_uuid:2,ppp,hhh

代码:

$ sed -e 's/device_uuid:\(.*\),/\1/' d
xxx,yyyttt
2,ppphhh

预期 o/p:

xxx
2

编辑1:

我在 AIX 上无法使用 grep -oP

使用 awk 失败:

d

device_uuid:xxx,yyy,ttt
ptr,ttt
device_uuid:2,ppp,hhh
total_uuid:5,jkl,mno
device_uuid:9

$ awk -F 'total_uuid:|,' '{print $2}' d
yyy
ttt
ppp
5

上述情况下的预期 o/p:

blank or device_uuid:xxx,yyy,ttt
blank or ptr,ttt
blank or device_uuid:2,ppp,hhh
5
blank or device_uuid:9

device_uuid: 不必是第一列,同样所有都可以是随机的,但我需要选择该变量对应的 vale 直到立即分隔符,

-- 剪切也失败,因为它只能接受一个字符分隔符。

-- $ perl -l -ne '/device_uuid:([\w\-]*?)\,/g and print($1)' d

perl 以上也失败了,因为如果 device_uuid 不在一行中,则该行在 o/p 中被删除,但它应该是 显示为空白

谢谢。

【问题讨论】:

    标签: linux perl shell aix


    【解决方案1】:

    它并不漂亮,但是几个 cuts 应该可以完成这项工作:

    $ echo "device_uuid:xxx,yyy,ttt" | cut -d":" -f2- | cut -d"," -f1
    xxx
    

    【讨论】:

    • $ echo "device_uuid:xxx,yyy,ttt" |剪切 -d"device_uuid:" -f2- | cut -d"," -f1 evice_uuid:xxx -- 我不能单独分隔:
    【解决方案2】:

    使用sed

    sed 's/^.*total_uuid:\([^,]*\).*$/\1/' file
    device_uuid:xxx,yyy,ttt
    ptr,ttt
    device_uuid:2,ppp,hhh
    5
    device_uuid:9
    

    使用grep -oP

    grep -oP 'device_uuid:\K[^,]+' file
    xxx
    2
    

    【讨论】:

    • 如何在 AIX 中使用 -oP ?它不支持这些选项?
    • 好吧,您没有提到 AIX。无论如何,你可以使用我的 awk 命令。
    猜你喜欢
    • 1970-01-01
    • 2019-08-01
    • 1970-01-01
    • 2022-10-13
    • 1970-01-01
    • 2017-08-20
    • 1970-01-01
    • 2011-11-02
    • 1970-01-01
    相关资源
    最近更新 更多