M. Ebner
M. Ebner

Reputation: 33

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!

Upvotes: 2

Views: 637

Answers (2)

tripleee
tripleee

Reputation: 189648

There is no trivial solution to this with Bash builtins as far as I know, but if that's what you need, you could do something like this.

ligne="this.is/just(an]example"
array=()
while true; do
    for delim in '}' '//' ')' '(' ' ' '{' '[' ']' '.' ';' '/"' ','; do
        frag=${ligne#*"$delim"}
        [ "$frag" = "$ligne" ] || break
    done
    [ "$frag = "$ligne" ] && break
    head=${ligne%"$frag"}
    array+=("${head%"$delim"}" "$delim")
    ligne=$frag
done

Upvotes: 0

anubhava
anubhava

Reputation: 785551

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

Upvotes: 2

Related Questions