Bash脚本,用于更改变量中的字符串

时间:2018-10-16 13:58:25

标签: bash awk sed

我在bash中有两个变量:

在第一个变量中,字段分隔符为(,) 在第二个变量中,字段分隔符也是(,)

在名为VAR1的第一个变量中,我有:

Maria Debbie Annie,Chewbakka Zero,Yoda One,Vader 001

在名为VAR2的第二个变量中:

"number":"11112",Maria Debbie Annie
"number":"11113",Maria Debbie Annie Lisa
"number":"33464",Chewbakka Zero
"number":"22465",Chewbakka Zero Two
"number":"34534",Christine Ashley
"number":"45233",Yoda One
"number":"45233",Yoda One One
"number":"38472",Susanne Ann
"number":"99999",Vader 001
"number":"99991",Vader 001 001
"number":"99992",Vader 001 002

变量VAR3中所需的输出:

"number":"11112","number":"33464","number":"45233","number":"99999"

因此,基本上我需要将输出中的名称从第一个变量的顺序更改为"number":"somenumber"。 还有非常相似的字符串也很重要,因此 Yoda One != Yoda One OneChewbakka Zero不等于Chewbakka Zero Two

VAR2包含的行数比列出的要多得多,我只是想表明脚本需要找到VAR1VAR2之间的精确匹配项。 感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

检查一下。

> echo "$VAR1"
Maria Debbie Annie,Chewbakka Zero,Yoda One,Vader 001
> echo "$VAR2"
"number":"11112",Maria Debbie Annie
"number":"11113",Maria Debbie Annie Lisa
"number":"33464",Chewbakka Zero
"number":"22465",Chewbakka Zero Two
"number":"34534",Christine Ashley
"number":"45233",Yoda One
"number":"45233",Yoda One One
"number":"38472",Susanne Ann
"number":"99999",Vader 001
"number":"99991",Vader 001 001
"number":"99992",Vader 001 002
> export VAR1A=$(echo $VAR1| sed 's/,/$\|/g' | sed 's/$/\$/g')
> echo "$VAR1A"
Maria Debbie Annie$|Chewbakka Zero$|Yoda One$|Vader 001$
> echo "$VAR2"  | egrep "$VAR1A" | awk -F"," ' { printf("%s,",$1)} END { printf("\n") } ' | sed 's/.$//g'
"number":"11112","number":"33464","number":"45233","number":"99999"
>