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"
The command for the extraction of substring is a build-in bash command, and so it is very good to use for performance perspective. The syntax of the substring extraction can be defined as: ${variable:offset:length}
Using the cut Command Specifying the character index isn't the only way to extract a substring. You can also use the -d and -f flags to extract a string by specifying characters to split on. The -d flag lets you specify the delimiter to split on while -f lets you choose which substring of the split to choose.
-c (column): To cut by character use the -c option. This selects the characters given to the -c option.
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
Possible use awk with -
delimiter
echo "abc-def-ghi" | awk -F'-' '{print $2}'
-F - what field separator to use.
{print $2} - print second position
Let's say you have:
s="abc-def-ghi"
ch='-'
Using BASH read
builtin:
IFS="$ch" read -ra arr <<< $s && echo "${arr[1]}"
Or, using BASH regex:
re="$ch([^$ch]*)$ch"
[[ $s =~ -([^-]*)- ]] && echo "${BASH_REMATCH[1]}"
Output:
def
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With