String 提取字符串的两部分
我有一个字符串,其中包含一个命令的输出,如下所示:String 提取字符串的两部分,string,bash,extract,cut,String,Bash,Extract,Cut,我有一个字符串,其中包含一个命令的输出,如下所示: 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 $2}') string2=$(echo "max.
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 $2}')
string2=$(echo "max. bit rate: ('2.5 MBit/s', '16.7 MBit/s')" | awk -F"'" '{print $4}')
带切口:
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个字段。使用awk:
string1=$(echo "max. bit rate: ('2.5 MBit/s', '16.7 MBit/s')" | awk -F"'" '{print $2}')
string2=$(echo "max. bit rate: ('2.5 MBit/s', '16.7 MBit/s')" | awk -F"'" '{print $4}')
带切口:
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
2.5 MBit/s 16.7 MBit/s
使用正则表达式:
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
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
yourString=“最大比特率:('2.5 MBit/s','16.7 MBit/s')”
如果在bash
中这样读取rate1 rate2 p>,而不启动任何额外的外部进程:
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
yourString=“最大比特率:('2.5 MBit/s','16.7 MBit/s')”
IFS=“””读“rate1”读“rate2”读到现在为止你都试了些什么?给我们看看代码!你以前试过什么?给我们看看代码!