extracting floating numbers from variable using bash's builtin string chopping
Hi. I'm wanting to use bash3 to chop up some strings! :-)
Here's the string I want to chop: Code:
C9-1.4-1.6 I'm wanting to chop out the 1.4 and the 1.6. The 1.6 is simple enough with something like Code:
echo "${window##*-}" What I'm having trouble with is getting the 1.4 out of there. I can do it with a simple Code:
echo "${window:3:3}" Code:
C10-1.4-1.6 Code:
-1. So, to summarize, I have a string that contains two 2-digit floating point numbers, separated off by dashes(-), and I want to extract these and only these strings. Any help appreciated! billywayne |
Hello. Here is one solution (surely not the only one and surely not the best):
Code:
var='C9-1.4-1.6' Cheers |
echo "${window#*-}"
If you use only one hashmark, it stops at the first match. Edit: After seeing the above post, I think I misunderstood the question. You want to extract only the middle number? I don't think that's generally doable in one step through parameter substitution (except by the 3:3 column matching you already know about). You have to use multiple steps as above, or an external tool like grep, sed, or awk for that. |
OK. Thanks for the replies.
I was hoping for something like a Code:
echo ${var#*-%-*} billywayne |
Here's a way that technically extracts the everything in one step, although you can't echo it in the same command.
Code:
window='C9-1.4-1.6' thought of something like ${var#*-%-*}, kind of ugly though Code:
shopt -s extglob # requires extended globs |
Code:
# IFS="-" |
Quote:
Quote:
In the end though, it's seems obvious that there's no way to do it in a single line. It's going to take two or more commands to extract the middle portion no matter what you try. I think ntubski's solution above is the cleanest one, personally, if you really need it all done in one operation. Otherwise, the simplest solution is probably just to step it through two iterations of variable expansion. Code:
var="C9-1.4-1.6" |
Quote:
Code:
unset IFS |
Quote:
It's not necessarily a fatal flaw, but it could cause problems if you're not careful. |
Quote:
|
Quote:
str1=$(echo $window | cut -d'-' -f1) str2=$(echo $window | cut -d'-' -f2) str3=$(echo $window | cut -d'-' -f3) |
Quote:
|
Hello :)
Just to add another parsing technique (ntubski's ${var//@(+([^-])-|-+([^-]))/} is already a magnificent solution), how about Code:
$ a="C9-1.4-1.6" Charles |
Quote:
Quote:
|
Thanks ntubski :)
Quote:
Quote:
Code:
oIFS="$IFS" Charles |
All times are GMT -5. The time now is 04:36 AM. |