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 :)

Kamil Maciorowski
  • 69,815
  • 22
  • 136
  • 202
Random Guy
  • 5
  • 1
  • 4

3 Answers3

1

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
  • 5,319
  • 5
  • 20
  • 20
  • 1
    As Kamil Maciorowski noted, it's theoretically faster to do the processing inside the shell. But using awk is much clearer and easier to understand -- and change if needed. Bending over backwards to be fractionally faster is false economy here. If you really need that performance boost, don't do this in an interpreted scripting language at all. – mpez0 Jul 21 '22 at 13:02
  • 1
    @mpez0, `awk` will show full speed on more complex operations, this is just read, separate and print. And for me do not worth the effort to write it in `C` for example :) – Romeo Ninov Jul 21 '22 at 13:10
  • 1
    I'm trying to agree with your post and show that the convoluted do-it-all-in-bash isn't worth the hassle. That's why I upvoted it. – mpez0 Jul 21 '22 at 13:48
1

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
  • 11
  • 1
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.)

u1686_grawity
  • 426,297
  • 64
  • 894
  • 966