Bash: substring from first occurrence of a character to the second occurrence

Stephen Walsh picture Stephen Walsh · Aug 28, 2017 · Viewed 7.3k times · Source

In bash, how do I get a substring of everything from the first occurrence of a character to the second occurrence of the same character.

Example...

Input String = "abc-def-ghi"

Character = "-"

Desired Output String = "def"

Answer

chepner picture chepner · Aug 28, 2017

I would use two parameter expansions.

str="abc-def-ghi"
tmp=${str#*-}  # Remove everything up to and including first -
result=${tmp%%-*} # Remove the first - and everything following it