【问题标题】:Bash RegEx and Storing Commands into a VariableBash RegEx 并将命令存储到变量中
【发布时间】:2019-10-31 16:33:42
【问题描述】:

在 Bash 中,我有一个数组 names,其中包含字符串值

Dr. Praveen Hishnadas
Dr. Vij Pamy
John Smitherson,Dr.,Service Account
John Dinkleberg,Dr.,Service Account

我只想捕获名称

Praveen Hishnadas
Vij Pamy
John Smitherson
John Dinkleberg

并将它们存储回原始数组中,覆盖其未经处理的版本。

我有以下 sn-p 代码 请注意,我正在 Perl (-P) 中执行正则表达式

for i in "${names[@]}"
do
        echo $i|grep -P  '(?:Dr\.)?\w+ \w+|$' -o | head -1

done

产生输出

Dr. Praveen Hishnadas
Dr. Vij Pamy
John Smitherson
John Dinkleberg

问题:

1) 我是否错误地使用了环视命令?:?我正在尝试选择匹配“博士”。尽管 没拍到

2) 我如何将该回显的结果存储回数组名称中?我尝试将其设置为

i=echo $i|grep -P  '(?:Dr\.)?\w+ \w+|$' -o | head -1

i=$(echo $i|grep -P  '(?:Dr\.)?\w+ \w+|$' -o | head -1)

i=`echo $i|grep -P  '(?:Dr\.)?\w+ \w+|$' -o | head -1`

但无济于事。我 2 天前才开始学习 bash,我觉得我的语法有点不对劲。任何帮助表示赞赏。

【问题讨论】:

    标签: arrays regex string bash


    【解决方案1】:

    您的前瞻显示“包括Dr.,如果它在那里”。您可能想要像(?!Dr\.)\w+ \w+ 这样的负前瞻。我会扔一个领先的\b主播奖金。

    names=('Dr. Praveen Hishnadas' 'Dr. Vij Pamy' 'John Smitherson,Dr.,Service Account' 'John Dinkleberg,Dr.,Service Account')
    
    for i in "${names[@]}"
    do
            grep -P  '\b(?!Dr\.)\w+ \w+' -o <<<"$i" |
            head -n 1
    done
    

    您提供的示例无关紧要,但您基本上应该始终引用您的变量。见When to wrap quotes around a shell variable?

    也许还有谷歌"falsehoods programmers believe about names".

    要更新您的数组,请遍历数组索引并分配回数组。

    for((i=0;i<${#names[@]};++i)); do
        names[$i]=$(grep -P  '\b(?!Dr\.)\w+ \w+|$' -o <<<"${names[i]}" | head -n 1)
    done
    

    【讨论】:

    • 感谢您的所有帮助,这很好!尽管让我感到困惑的一件事是,如果我输入“Dr Alex Jones”并修改正则表达式以使句点字符可选,例如 (?!Dr\.*) 它无法识别模式并输出“Dr Alex”而不是
    • 尝试将其更改为(?!Dr\W)或类似的东西。当您处理各种创造性的人类混淆时,正则表达式开始崩溃,但这应该很容易。
    【解决方案2】:

    这样的正则表达式怎么样?

    (?:^|\.\s)(\w+)\s+(\w+)
    

    Regex Demo

    (?:             # Non-capturing group
       ^|\.\s       # Start match if start of line or following dot+space sequence
    )
    (\w+)           # Group 1 captures the first name
    \s+             # Match unlimited number of spaces between first and last name (take + off to match 1 space)
    (\w+)           # Group 2 captures surname.
    

    【讨论】:

    • 不幸的是,这会产生:.普拉文·希纳达斯,。 Vij Pamy, John Smitherson, John Dinkleberg 我相信我的问题可能是在 Perl 模式下执行它
    猜你喜欢
    • 2015-11-08
    • 2012-04-03
    • 2021-11-19
    • 1970-01-01
    • 2011-02-13
    • 1970-01-01
    • 2012-03-02
    • 1970-01-01
    • 2022-10-19
    相关资源
    最近更新 更多