Search code examples
bashsplitdelimiterifs

Bash: split on delimiter but keep the delimiter


I would like to split a String into an array using delimiters and keep those delimiters. I tried using IFS but it re,oves the delimiters.

For example:

ligne="this.is/just(an]example"
IFS='}|//|)|(| |{|[|]|.|;|/"|,' read -ra ADDR <<< "$ligne"
for i in "${ADDR[@]}"; do
   echo $i
done

I want the result to be like this:

this
.
is
/
just
(
an
]
example

Thanks for your help!


Solution

  • You may use grep with -o option:

    grep -oE '[^][^./(){};:,"]+|[][^./(){};:,"]' <<< "$ligne"
    

    this
    .
    is
    /
    just
    (
    an
    ]
    example
    

    Regex in use is alternation based with 2 alternations:

    • [^][^./(){};:,"]+: Match 1+ of any character that is not in character class
    • |: OR
    • [][^./(){};:,"]: Match any character that is in the character class