从Linux中的字符串中提取所需信息

时间:2015-06-23 19:15:21

标签: linux bash

下面是我得到的字符串,现在我想从这一行中提取两个3840,我应该在Bash脚本中使用什么命令?

  

Stream #0:0(eng): Video: h264 (High) (avc1 / 0x31637661), yuv420p, 3840x3840 [SAR 1:1 DAR 1:1], 100072 kb/s, 59.94 fps, 59.94 tbr, 60k tbn, 119.88 tbc

4 个答案:

答案 0 :(得分:1)

使用带管道的切割:

newstring=`echo "<your string here>"|cut -f3 -d","`

注意背景!你的新闻字符串应包含&#34; 3840x3840 [SAR 1:1 DAR 1:1]&#34;,现在你可以做另一个剪辑和管道:

result=`echo $newstring|cut -f1 -d" "`

或者把它们放在一起:

result=`echo "<your string here>"|cut -f3 -d","|cut -f1 -d" "` 

你现在应该有&#34; 3840x3840&#34;。所有这些都是非常基本的&#34; cut&#34;命令以及管道 - 检查这些选项的联机帮助页以及更多切割选项。

答案 1 :(得分:1)

您可以将其传输到grep grep -oE "[1-9][0-9]*x[1-9][0-9]*",这将提取3840x3840

以下是一个在单独变量中检索宽度和高度的示例:

INPUT="Stream #0:0(eng): Video: h264 (High) (avc1 / 0x31637661), yuv420p, 1024x768 [SAR 1:1 DAR 1:1], 100072 kb/s, 59.94 fps, 59.94 tbr, 60k tbn, 119.88 tbc"
RES=`echo $INPUT | grep -oE "[1-9][0-9]*x[1-9][0-9]*"` # 1024x768
WIDTH=`echo $RES | cut -f1 -dx` # get the first column, where 'x' is the separator
HEIGHT=`echo $RES | cut -f2 -dx` # get the second column, where 'x' is the separator
echo $WIDTH # 1024 in this example
echo $HEIGHT # 768 in this example

答案 2 :(得分:0)

如果你想要NxM,其中N = M,你可以使用grep和后引用。

grep -Eo '([0-9]+)x\1'

答案 3 :(得分:0)

您可以使用bash rematch

val="Stream #0:0(eng): Video: h264 (High) (avc1 / 0x31637661), yuv420p, 3840x3840 [SAR 1:1 DAR 1:1], 100072 kb/s, 59.94 fps, 59.94 tbr, 60k tbn
, 119 .88 tbc"
[[ $val =~ ([0-9]{4})x([0-9]{4}) ]] 
         echo ${BASH_REMATCH[1]}
         echo ${BASH_REMATCH[2]}