I have a string formatted as below
Walk Off the Earth - Somebody That I Used to Know
[playing] #36/37 1:04/4:05 (26%)
volume: n/a repeat: off random: on single: off consume: off
Now, from the above string I need to extract 36
from #36/37
.
First thing I did was to extract #36/37
from second line using
echo "above mentioned string" | awk 'NR==2 {print $2}'
Now, I want to extract 36
from the above extracted part for that I did
echo `#36/37` | sed -e 's/\//#/g' | awk -F "#" '{print $2}'
which gave me 36
as my outptut.
But, I feel that using both sed and awk
just to extract text from #36/37
is but of a overkill. So, is there any better or shorter way to achieve this.
Split the field on the pound and slash characters into an array and retrieve the required element.
awk 'NR==2 {split($2, arr, "[#/]"); print arr[2]}'
This answer takes advantage of bash's built-in extended regular-expression syntax using the =~
test operator. (I say test
, but don't expect it to work with the test
command. It only works with the [[
keyword.)
mini:~ michael$ cat foo
Walk Off the Earth - Somebody That I Used to Know
[playing] #36/37 1:04/4:05 (26%)
volume: n/a repeat: off random: on single: off consume: off
mini:~ michael$ [[ $(<foo) =~ \#[[:digit:]]{2} ]] && echo "${BASH_REMATCH[0]#\#}"
36
When you boil it down, this is simply a regular expression that matches the two digits after a pound sign, and saves them in the zeroth element of the BASH_REMATCH
array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With