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
  • 322
  • 1
    Cross-posted on Stackoverflow: http://stackoverflow.com/questions/34013860/how-to-extract-foo-from-foo-bar-baz-in-bash – John1024 Dec 01 '15 at 07:10

3 Answers3

3
$ str="foo-bar-baz"

$ echo "${str%%-*}"
foo

$ echo "${str##*-}"
baz

$ var="${str#*-}"
$ echo "$var"
bar-baz
$ echo "${var%-*}"
bar
heemayl
  • 56,300
0

This might extract foo from the string.

$ str="foo-bar-baz"
str= ${str%-*} #this will get the part foo-bar
str= ${str%-*} #this will fetch foo from the string foo-bar
echo $str
jasonwryan
  • 73,126
0

@heemayl already gave the correct answer, but to add the reference and explanation:

From man bash:

   ${parameter%word}
   ${parameter%%word}
          Remove matching suffix pattern.  The word is expanded to produce a pattern just  as  in  pathname  expansion.   If  the  pattern
          matches a trailing portion of the expanded value of parameter, then the result of the expansion is the expanded value of parame-
          ter with the shortest matching pattern (the ‘‘%’’ case) or the longest matching pattern (the ‘‘%%’’ case) deleted.

You were only using a single % sign, so the shortest match was removed instead of the longest match.

And as a side note, I recently read a very accurate observation that people who learn bash and don't learn awk often end up using bash for text-processing jobs where it is entirely and completely the wrong tool. I learned 90% of awk (everything but the more advanced functions) in about 5 hours—one evening and one morning.

If all you're doing is stripping out this one string to use as a file name or a command argument or something, then of course that's fine and that's why the functionality exists in bash at all. However, if you're doing more advanced and complicated string juggling, I highly recommend spending a day learning awk. It will pay off several dozen times over.

(I mention this mostly because your tags make it seem likely that awk would be a bigger help to you than bash string juggling.)

Wildcard
  • 36,499