Bash - get String between two characters

Viewed 549

how can i get the string between two specific characters, only in bash [with out using grep or sed]

e.g

input=hostname~web:sit

I want to extract web from the above input

${hostname#*~} gives me output as web:sit, but i need only web in the output

From the other post i can see

% strips from end of $var, up to pattern. But not sure how to apply it.

Any help please

3 Answers

Do it in two steps:

input=hostname~web:sit

rightpart=${input#*~}   # remove prefix up to "~" (included)
output=${rightpart%:*}  # remove suffix from ":" (included)

echo $output

Using extglob in bash, you can do this in single step:

shopt -s extglob
input='hostname~web:sit'
echo "${input//@(*~|:*)/}"

web

Here @(*~|:*) matches a substring from start to ~ character OR a substring from : to end. Using // we replace all such instances with an empty string.


There is a sed solution as well:

sed -E 's/.*~([^:]+):.*/\1/' <<< "$input"

web

Another option, using cut wich is available from the GNU Core Utilities:

  1. Get all behind ~
  2. Get all before :
input='hostname~web:sit'
echo "$input" | cut -d '~' -f2 | cut -d ':' -f1
# web

Try it online!

Related