Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract string between two characters in bash

Tags:

string

bash

sed

awk

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.

like image 444
RanRag Avatar asked Jul 07 '12 20:07

RanRag


2 Answers

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]}'
like image 54
Dennis Williamson Avatar answered Nov 04 '22 18:11

Dennis Williamson


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.

like image 4
kojiro Avatar answered Nov 04 '22 18:11

kojiro