提取字符串的 2 个部分

Extracting 2 parts of a String

我有一个字符串,其中包含如下命令的输出:

max. bit rate:      ('2.5 MBit/s', '16.7 MBit/s')

现在我需要在两个单独的字符串中提取“2.5 MBit/s”和“16.7 MBit/s”。

语言是bash。

使用 awk:

string1=$(echo "max. bit rate:      ('2.5 MBit/s', '16.7 MBit/s')" | awk -F"'" '{print }')
string2=$(echo "max. bit rate:      ('2.5 MBit/s', '16.7 MBit/s')" | awk -F"'" '{print }')

剪裁:

string1=$(echo "max. bit rate:      ('2.5 MBit/s', '16.7 MBit/s')" | cut -d"'" -f2)
string2=$(echo "max. bit rate:      ('2.5 MBit/s', '16.7 MBit/s')" | cut -d"'" -f4)

无论哪种方式,我们都只是用单引号拆分字符串并获取第 2 和第 4 个字段。

使用正则表达式:

x="max. bit rate:      ('2.5 MBit/s', '16.7 MBit/s')"
[[ $x =~ .*\'(.*)\'.*\'(.*)\'.* ]] && echo "${BASH_REMATCH[1]} ${BASH_REMATCH[2]}"

输出:

2.5 MBit/s 16.7 MBit/s

bash 中这样,无需启动任何额外的外部进程:

yourString="max. bit rate:      ('2.5 MBit/s', '16.7 MBit/s')"

IFS="'" read _ rate1 _ rate2 _ <<< "$yourString"

echo $rate1
2.5 MBit/s

echo $rate2
16.7 MBit/s

我将 IFS(输入字段分隔符)设置为单引号,然后执行 read,不需要的字段进入名为 _ 的虚拟(未使用)变量。