繁体   English   中英

Bash 正则表达式和将命令存储到变量中

[英]Bash RegEx and Storing Commands into a Variable

在 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

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

我有以下代码片段,说明我正在 Perl (-P) 中执行正则表达式

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

done

这产生了 output

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,我觉得我的语法有点不对劲。 任何帮助表示赞赏。

您的前瞻说“包括Dr.如果它在那里”。 您可能想要像(?.Dr\.)\w+ \w+这样的负前瞻。 我将投入领先的\b锚 aa 奖金。

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

您提供的示例无关紧要,但您基本上应该始终引用您的变量。 请参阅何时在 shell 变量周围加上引号?

也许还有谷歌“程序员相信名字的谎言”。

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

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

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

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

正则表达式演示

(?:             # 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.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM