Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

shell script command to split string using a variable delimiter

Tags:

bash

shell

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

like image 767
Soumya Avatar asked May 31 '26 18:05

Soumya


1 Answers

#!/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}"
like image 147
jekell Avatar answered Jun 03 '26 20:06

jekell