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

4

9

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"

Deckhouse answered 28/8, 2017 at 14:45 Comment(0)
D
6

Possible use awk with - delimiter

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

-F - what field separator to use.

{print $2} - print second position

Dyspnea answered 28/8, 2017 at 14:52 Comment(0)
K
11

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
Karmenkarna answered 28/8, 2017 at 16:6 Comment(0)
D
6

Possible use awk with - delimiter

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

-F - what field separator to use.

{print $2} - print second position

Dyspnea answered 28/8, 2017 at 14:52 Comment(0)
O
4

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
Octal answered 28/8, 2017 at 14:51 Comment(0)
M
1

Why not just use cut command like this:

str="abc-def-ghi"

echo $str | cut -f 2 -d "-"

, where -d option is a delimiter and -f option stands for fragment number (the first fragment number is 1, not 0 as it is common for arrays).

Marr answered 24/12, 2017 at 20:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.