【问题标题】:Variable in grep regexgrep 正则表达式中的变量
【发布时间】:2018-01-30 19:05:47
【问题描述】:
#! /bin/bash
NAME='joe'
FILE="joewhatever@gmail.com\nwhatever@joe.com\nwhateverjoe@gmail.com"
echo -e "$FILE" | grep "${NAME}*@"

我明白了:

whateverjoe@gmail.com 

我希望得到:

joewhatever@gmail.com
whateverjoe@gmail.com

然后放出来:

whatever@joe.com

【问题讨论】:

    标签: regex bash grep


    【解决方案1】:

    星号*前面没有点.

    #!/bin/bash
    NAME='joe'
    FILE="joewhatever@gmail.com\nwhatever@joe.com\nwhateverjoe@gmail.com"
    echo -e "$FILE" | grep "${NAME}.*@"
    

    joewhatever@gmail.com
    whatjoe@gmail.com

    【讨论】:

      【解决方案2】:

      在正则表达式中,* 是一个量词,表示前面模式的零次或多次重复。变量替换后,您的正则表达式为joe*@。这匹配jo,后跟零个或多个e,后跟@joewhatever@gmail.com 与该模式不匹配,因为它在 joe@ 之间有 whatever

      你希望joe.*@ 作为正则表达式——. 匹配任何字符,所以.* 表示匹配任意数量的字符。所以应该是"${NAME}.*@"

      echo -e "$FILE" | grep "${NAME}.*@"
      

      【讨论】:

        猜你喜欢
        • 2013-08-11
        • 2023-03-04
        • 1970-01-01
        • 1970-01-01
        • 2023-03-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多