LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (http://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Best way to do ${variable:-3:1} ? (http://www.linuxquestions.org/questions/linux-newbie-8/best-way-to-do-%24%7Bvariable-3-1%7D-714725/)

anonguy9 03-26-2009 09:45 PM

Best way to do ${variable:-3:1} ?
 
(in pure bash)

Expecting Ruby-like syntax is asking too much, I know.. but I'm trying to do this equivalent:

Code:

duration="6.27"
if [ ${duration:-3:1} = "." ]; then
  echo hey!
fi

This fails because "-3" is not valid.


I don't know how to be sneaky and get the exit code of a substitution. This can't work since the setting of duration is a success and returns 0.

Code:

duration=${duration#*.}
if [ ! $? = 0 ]; then
  echo hey!
fi


My solution:

I could research iterating through the string in some other way, but converting it into an array seems sensible to me.

Props to this post for the hint.

Code:

string="1234567"
array=( )
for i in $(seq 0 $((${#string} - 1))); do
  array=( "${array[@]}" "${string:$i:1}" )
done


# Now, since this is impossible:
# ${duration[-3]}

# Count the number of elements.
element_count=${#array[*]}

# Third from the last would be:
my_element_number=$(( $element_count - 3 ))

# And that element in the array would be:
echo ${array[my_element_number]}


So.. My questions are..

- Is my solution sensible?

- Is there a better way to do this (in pure bash) ?
-- Regular expressions are possible, and I think that working with them on my variable would be best. But I couldn't wrap my brain around that. I'm positive this could all be wrapped into a oneliner. There are some great examples in tldp but none seem quite like what I want (third from the right).

- Has anyone already built a nicer function to work with strings as though they were arrays?

Kenhelm 03-27-2009 06:44 AM

A negative position parameter needs to be escaped with parentheses or a space.
The escaping avoids it being mistaken for this other type of substitution
${var:-value} Use 'var' if set; otherwise, use 'value'.
Code:

string=1234567
echo ${string:(-3):1}
5
echo ${string: -3:1}
5


anonguy9 03-27-2009 11:03 AM

Haha! So simple!

Well, I guess I learned more about arrays and iteration with my other solution. Hehe.

Thanks for the help.


All times are GMT -5. The time now is 12:44 PM.