Question

I have one line string like

Stream #0:0(und): Video: h264 (High) (avc1 / 0x31637661), yuv420p, 720x480 [SAR 32:27 DAR 16:9], 2286 kb/s, 29.97 fps, 29.97 tbr, 30k tbn, 59.94 tbc (default)

I know that I can obtain " 2286 kb/s" by using cut command.

foo='Stream #0:0(und): Video: h264 (High) (avc1 / 0x31637661), yuv420p, 720x480 [SAR 32:27 DAR 16:9], 2286 kb/s, 29.97 fps, 29.97 tbr, 30k tbn, 59.94 tbc (default)'
echo $foo | cut -d ',' -f 4

But if the field number of " 2286 kb/s" differs, I can't use cut command. Moreover the unit might be changed like " 16 mb/s".

I think I need to use grep, egrep, or sed with regular expression to obtain the string. But since I'm not familiar with regular expression, I have no idea to how to use them. Please help me

Was it helpful?

Solution

You could use grep:

grep -oE '[0-9]+ [km]b/s' <<< "$foo"

or sed:

sed 's|.* \([0-9]* [km]b/s\).*|\1|' <<< "$foo"

OTHER TIPS

You could use awk like this:

awk 'BEGIN{RS=", "}/[km]b\/s/' <<<"$foo"

RS is the record separator, which means every comma separated value will be treated as a separate record. This will print the record when it contains a k or m followed by b/s.

Another way of using grep:

echo $foo | tr ',' '\n' | grep -e /s$

This just looks for anything ending in /s (so mb/s, kb/s gb/s, whatever) on everything between two commas (we swapped commas for newlines with tr)

Here is a demonstration of it in action:

➜  ~  foo='Stream #0:0(und): Video: h264 (High) (avc1 / 0x31637661), yuv420p, 720x480 [SAR 32:27 DAR 16:9], 2286 kb/s, 29.97 fps, 29.97 tbr, 30k tbn, 59.94 tbc (default)'
➜  ~  echo $foo | tr ',' '\n' | grep -e /s$
 2286 kb/s
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top