1

I'm trying to extract foo from the string "foo-bar-baz" in bash.

Any ideas how to do it using string substitution or something similar (without external tools).

I tried this but it didn't work:

$ str="foo-bar-baz"
$ echo ${str%-*}
foo-bar

This also not work:

$ str="foo-bar-baz"
$ echo ${str#*-}
bar-baz

Any ideas how to get just bar?

bodacydo
  • 69,885
  • 86
  • 222
  • 312
  • Cross-posted on Unix+Linux: http://unix.stackexchange.com/questions/246539/how-to-extract-foo-from-foo-bar-baz-in-bash – John1024 Dec 01 '15 at 07:10
  • Possible duplicate of [How do I remove the file suffix and path portion from a path string in Bash?](http://stackoverflow.com/questions/125281/how-do-i-remove-the-file-suffix-and-path-portion-from-a-path-string-in-bash) – John1024 Dec 01 '15 at 08:03

3 Answers3

1
str="foo-bar-baz"
echo ${str%%-*}

Output:

foo
Cyrus
  • 77,979
  • 13
  • 71
  • 125
  • See: [Shell Parameter Expansion](http://tiswww.case.edu/php/chet/bash/bashref.html#SEC32) section about `${parameter%%word}`. %% is greedy version of %. – Cyrus Dec 01 '15 at 06:35
0

You can also make use of substring replacement:

str="foo-bar-baz"
foostr=${str//-*/}  ## assign 'foo' to foostr
echo $foostr        ## 'foo'

note: with the omission of the closing /, the replacement string is taken as empty by the shell.

David C. Rankin
  • 75,900
  • 6
  • 54
  • 79
0

Using Bash regex matching:

#!/bin/bash
str="foo-bar-baz"
pat="([^-]*)-([^-]*)-.*"
[[ $str =~ $pat ]]
echo "${BASH_REMATCH[1]}" # foo
echo "${BASH_REMATCH[2]}" # bar
Jahid
  • 19,822
  • 8
  • 86
  • 102