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

Potherca
  • 13,207
  • 5
  • 76
  • 94
Soumya
  • 1,833
  • 5
  • 34
  • 45

5 Answers5

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}"
jekell
  • 81
  • 1
  • 2
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
cforbish
  • 8,567
  • 3
  • 28
  • 32
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"
thom
  • 2,294
  • 12
  • 9
0
result=$(echo "${str}" | awk 'gsub("${var}","${var}\n")
petrus4
  • 616
  • 4
  • 7
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")'
$
gniourf_gniourf
  • 44,650
  • 9
  • 93
  • 104