正则表达式提取百分比

时间:2021-07-16 13:05:54

I have strings like the following: blabla a13724bla-bla244 35%

我有如下字符串:blabla a13724bla-bla244 35%

Notice that there is always a space before the percentage. I would like to extract the percentage number (so, without the %) from these strings using the Linux shell.

请注意,百分比之前总是有空格。我想使用Linux shell从这些字符串中提取百分比数(因此,没有%)。

6 个解决方案

#1


3  

Using sed:

使用sed:

echo blabla a13724bla-bla244 35% | sed 's/.*[ \t][ \t]*\([0-9][0-9]*\)%.*/\1/'

If you expect to have multiple percentages in a line then:

如果您希望在一行中有多个百分比,那么:

echo blabla 20% a13724bla-bla244 35% | \
   sed -e 's/[^%0-9 ]*//g;s/  */\n/g' | sed -n '/%/p'

#2


4  

Assuming you have GNU grep:

假设你有GNU grep:

$ grep -oP '\d+(?=%)' <<< "blabla a13724bla-bla244 35%"
35

#3


0  

You may try this regular expression:

你可以尝试这个正则表达式:

/\s(\d+%)/

#4


0  

You can try this

你可以试试这个

echo "blabla a13724bla-bla244 35%" | cut -d' ' -f3 | sed 's/\%//g'

NOTE: Assumption is the input is always in this format and percentage is 3rd token separated by space.

注意:假设输入始终采用此格式,百分比是以空格分隔的第三个标记。

#5


0  

Use this regular expression:

使用此正则表达式:

\s(\d{1,3})%

If you need it in shell, you can use sed or this perl one-liner:

如果你需要它在shell中,你可以使用sed或perl one-liner:

echo "blah 35%" | perl -pe "s/.*\s(\d{1,3})%/\1/g"
35

#6


0  

If you always have a number of continuous columns maybe you should try with awk instead of a regular expresion.

如果你总是有一些连续的列,你应该尝试使用awk而不是常规表达式。

cat file.txt |awk '{print $3}'  |cut -d "%" -f 1

With this code you obtain the third column.

使用此代码,您将获得第三列。

#1


3  

Using sed:

使用sed:

echo blabla a13724bla-bla244 35% | sed 's/.*[ \t][ \t]*\([0-9][0-9]*\)%.*/\1/'

If you expect to have multiple percentages in a line then:

如果您希望在一行中有多个百分比,那么:

echo blabla 20% a13724bla-bla244 35% | \
   sed -e 's/[^%0-9 ]*//g;s/  */\n/g' | sed -n '/%/p'

#2


4  

Assuming you have GNU grep:

假设你有GNU grep:

$ grep -oP '\d+(?=%)' <<< "blabla a13724bla-bla244 35%"
35

#3


0  

You may try this regular expression:

你可以尝试这个正则表达式:

/\s(\d+%)/

#4


0  

You can try this

你可以试试这个

echo "blabla a13724bla-bla244 35%" | cut -d' ' -f3 | sed 's/\%//g'

NOTE: Assumption is the input is always in this format and percentage is 3rd token separated by space.

注意:假设输入始终采用此格式,百分比是以空格分隔的第三个标记。

#5


0  

Use this regular expression:

使用此正则表达式:

\s(\d{1,3})%

If you need it in shell, you can use sed or this perl one-liner:

如果你需要它在shell中,你可以使用sed或perl one-liner:

echo "blah 35%" | perl -pe "s/.*\s(\d{1,3})%/\1/g"
35

#6


0  

If you always have a number of continuous columns maybe you should try with awk instead of a regular expresion.

如果你总是有一些连续的列,你应该尝试使用awk而不是常规表达式。

cat file.txt |awk '{print $3}'  |cut -d "%" -f 1

With this code you obtain the third column.

使用此代码,您将获得第三列。