0

There is this output i get:

Duration: 00:03:27.05, start: 0.000000, bitrate: 336 kb/s

I want to extract 00:03:27.05 from this whole string(Values Can Change).

So far I have tried:

String="Duration: 00:03:27.05, start: 0.000000, bitrate: 336 kb/s"

String="${String#:}" String="${String%,,*}" echo $String

It gives the desired results, but here I have to Declare String variable Two times and have to cut specific part of string separately.

So I Just want to Know an easiest and Straight-Forward approach to do it.

Thanks in Advance for Help :)

3 Answers3

2

You can try something like with awk:

awk -F'[ ,]' '{print $2}' input_file

Example:

echo "Duration: 00:03:27.05, start: 0.000000, bitrate: 336 kb/s"|awk -F'[ ,]' '{print $2}'
00:03:27.05
Romeo Ninov
  • 7,848
2

Assuming that this specific time pattern is the only one in your string, a very straightforward approach would be to simply use grep with the -P flag that allows us to interpret patterns as Perl-compatible regular expressions :

String="Duration: 00:03:27.05, start: 0.000000, bitrate: 336 kb/s"

echo $String | grep -oP "[0-9]{2}:[0-9]{2}:[0-9]{2}.[0-9]{2}"

This would output 00:03:27.05

weirty
  • 21
0

Bash lets you use POSIX ERE regular expressions:

String="Duration: 00:03:27.05, start: 0.000000, bitrate: 336 kb/s"

if [[ $String =~ Duration:\ ([^,]+), ]]; then String=${BASH_REMATCH[1]} fi

In plain Bourne shell, /bin/expr is the standard tool:

expr "$String" : 'Duration: \([^,]*\),'

(Note that expr uses BRE regex syntax instead of ERE, so grouping uses \( \) and the + operator is unavailable. Also, expr's regex is implicitly anchored to the beginning of the string, whereas =~ searches anywhere within the string.)

grawity
  • 501,077