shell脚本命令使用变量分隔符拆分字符串

Sou*_*mya 2 bash shell

我想在具有以下条件的bash shell脚本中拆分字符串.

1)分隔符是一个变量

2)分隔符是多个haracater

例:

A quick brown fox
var=brown
Run Code Online (Sandbox Code Playgroud)

我想将字符串拆分为A quick,brown fox但是使用变量var作为分隔符而不是brown

小智 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}"
Run Code Online (Sandbox Code Playgroud)