2

I want to split a string in a bash shell script with the following conditions.

1) The delimiter is a variable

2) The delimiter is multicharacater

example:

A quick brown fox
var=brown

I want to split the string into A quick and brown fox but using the variable var as delimiter and not brown

2
  • Did you want the delimiter to be removed or remain in the output? Commented Nov 10, 2013 at 3:07
  • see stackoverflow.com/questions/918886/… Commented Nov 10, 2013 at 3:16

5 Answers 5

8
#!/bin/bash

#variables according to the example
example="A quick brown fox"
var="brown"

#the logic (using bash string replacement)
front=${example%${var}*}
rear=${example#*${var}}

#the output
echo "${front}"
echo "${var}"
echo "${rear}"
Sign up to request clarification or add additional context in comments.

1 Comment

I test this using dash (sh) and it worked too. Very nice solution!
1

This sounds like what you are actually asking for (keep the delimiter in results):

str="A quick brown fox"
var="brown "
result=$(echo ${str} | sed "s/${var}/\\n${var}/g")

This is what you might have actually meant (remove the delimiter from the original string):

str="A quick really brown fox"
var=" really "
result=$(echo ${str} | sed "s/${var}/\\n/g")

This is something you can run to verify the results:

IFS=$'\n'
for item in ${result[@]}; do
    echo "item=${item}."
done

Comments

1

It can be done with 100% bash internal commands:

#!/bin/bash

#variables according to the example
example="A quick brown fox"
var="brown"

#the logic (using bash string replacement)
front=${example%"$var" *}
rear=${example/"$front"/}

#the output
echo "$front"
echo "$rear"

Comments

0
result=$(echo "${str}" | awk 'gsub("${var}","${var}\n")

Comments

0

Your question isn't very well posed, because your splitting should show "A quick " (with a trailing space). You don't even tell how you want the output to be given (in an array, in two separate variables...). Never, let me rephrase your question in my way, and answer this rephrased question. If it's not what you want, you'll know how to modify your original post.

Given a string s and a regex var, give an array a with two fields a[0] and a[1] such that the concatenation of the two fields of array a is s and such that a[1] =~ ^var.* with a[1] being the minimal (non-greedy) match.

Well, this already exists in bash:

[[ $s =~ ^(.*)($var.*)$ ]]
a=( "${BASH_REMATCH[@]:1}" )

Look:

$ s="A quick brown fox"
$ var=brown
$ [[ $s =~ ^(.*)($var.*)$ ]]
$ a=( "${BASH_REMATCH[@]:1}" )
$ declare -p a
declare -a a='([0]="A quick " [1]="brown fox")'
$

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.