Search code examples
arraysbashsubstringcut

Cut substrings between 2 characters and loop through them


I have the following string:

<(name:John,sirname:Doe),(country:United States)>

And I want to loop through the values between parenthesis, previously removing < and >. First cycle will give name:John,sirname:Doe, and the second one country:United States. But it can have any amount of values. I don't want to use any libraries or things that don't come preinstalled in linux distros.


Solution

  • You can use gnu awk with FPAT to break each field using (...) pattern:

    s='<(name:John,sirname:Doe),(country:United States)>'
    
    awk -v FPAT='\\([^)]+\\)' '{
    for (h=1; h<=NF; h++) {gsub(/[()]/, "", $h); print $h}}' <<< "$s"
    
    name:John,sirname:Doe
    country:United States