Skip to content
Advertisement

bash: string value based entries filtering

I have this check in my script:

[[ $KEY == contact@(s|_groups) ]] && CONFIG[$KEY]="$VALUE"

It is writing lines that contain contact* from one file to an array. How can I add another check that will skip the xi* values in that line and write it in the array?

I tried something like:

[[ $KEY == contact@(s|_groups) ]] && [[ $VALUE != "xi*" ]] && CONFIG[$KEY]="$VALUE"

But it is not working for me. :/

Advertisement

Answer

The first file looks like this:

…
    contacts                        Marko Geršić,Mijo,nagiosadmin,Patrick,ximgersic
…

The second file needs to look like this:

…
    contacts                        Marko Geršić,Mijo,nagiosadmin,Patrick
…

So, without the xi* in the contact* lines.

Since the xi* is at the end of the $VALUE, you can simply use the bash Parameter Expansion Remove matching suffix pattern:

  [[ $KEY == contact@(s|_groups) ]] && CONFIG[$KEY]="${VALUE%,xi*}"

xi* values aren´t always at the end of the line

If the xi* is amid the $VALUE elements, you could use Pattern substitution:

  [[ $KEY == contact@(s|_groups) ]] && CONFIG[$KEY]="${VALUE/,xi*([^,])}"

and if there are multiple xi* values?

To delete multiple xi* elements, you just have to double the / above:

  [[ $KEY == contact@(s|_groups) ]] && CONFIG[$KEY]="${VALUE//,xi*([^,])}"
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement