Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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"

like image 218
Stephen Walsh Avatar asked Aug 28 '17 14:08

Stephen Walsh


People also ask

How do I extract a substring in bash?

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}

How do you slice a string in bash?

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.

How trim a string in Linux?

-c (column): To cut by character use the -c option. This selects the characters given to the -c option.


3 Answers

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
like image 98
chepner Avatar answered Oct 16 '22 19:10

chepner


Possible use awk with - delimiter

echo "abc-def-ghi" | awk -F'-' '{print $2}'

-F - what field separator to use.

{print $2} - print second position

like image 5
beliy Avatar answered Oct 16 '22 19:10

beliy


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
like image 2
anubhava Avatar answered Oct 16 '22 19:10

anubhava