【问题标题】:Extract sub-string from strings based on condition with shell command line使用shell命令行根据条件从字符串中提取子字符串
【发布时间】:2020-05-16 05:28:10
【问题描述】:

我在myfile 中有这样的行:

mount -t cifs //hostname/path/ /mount/path/ -o username='xxxx',password='xxxxx'

我需要根据条件“从// 开始直到下一个空格包括//”从中提取子字符串。

我无法解析位置,因为它在所有匹配的行中都不相同。

到目前为止,我已经使用 grep 的 perl 断言提取了子字符串,但结果没有返回 //

我使用的这段代码是

cat myfile | grep " cifs " | grep -oP "(?<=/)[^\s]*" | grep -v ^/

输出:

hostname/path/

预期输出:

//hostname/path/

有没有办法通过修改 perl 正则表达式来获得所需的输出,也许是其他方法?

【问题讨论】:

  • 试试sed -En '/ cifs /{s,.*(//[^[:space:]]+).*,\1,p}' file,或grep -oE '//[^[:space:]]+' file

标签: regex bash shell perl grep


【解决方案1】:

简单的 bash 一行解决方案

grep " cifs " myfile | sed -e "s/ /\n/g" | grep '^\/\/' 

【讨论】:

    【解决方案2】:

    您可以考虑使用一些非基于 PCRE 的解决方案,例如

    sed -En '/ cifs /{s,.*(//[^[:space:]]+).*,\1,p}' file
    grep -oE '//[^[:space:]]+' file
    

    grep 解决方案只是从 file 中提取所有出现的 // 和 1+ 个非空白字符。

    sed 解决方案查找包含 cifs 的行,然后提取最后一次出现的 // 和这些行之后的 1+ 个非空白字符。

    【讨论】:

      【解决方案3】:

      以下命令应该按照您的要求进行

      grep cifs myfile | cut -d ' ' -f 4

      grep cifs myfile | nawk '{print $4}'

      awk '/cifs/ { print $4 }' myfile

      perl -ne "print $1 if /cifs\s+(\S+)/" myfile

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-08-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-04-01
        • 2015-05-10
        • 2017-01-31
        • 1970-01-01
        相关资源
        最近更新 更多