2

我正在尝试从使用 bash 运行的负载中提取动态。我已经到了获得我想要的字符串的地步,现在我想从中提取某些可能会有所不同的信息。返回的字符串如下:

Records: 2910 Deleted: 0 Skipped: 0 Warnings: 0

每个数字的长度都可以并且将会有所不同,但整体结构将保持不变。我想要做的是能够获取这些数字并将它们加载到一些 bash 变量中,即:

RECORDS=??
DELETED=??
SKIPPED=??
WARNING=??

在正则表达式中,我会这样做:

Records: (\d*?) Deleted: (\d*?) Skipped (\d*?) Warnings (\d*?)

并在我的变量中使用 4 个组。

4

5 回答 5

4

您可以在 Bash 版本 >= 3.2 中使用正则表达式匹配:

[[ $line =~ ([[:digit:]]+).*([[:digit:]]+).*([[:digit:]]+).*([[:digit:]]+) ]]

RECORDS=${BASH_REMATCH[1]}
DELETED=${BASH_REMATCH[2]}
SKIPPED=${BASH_REMATCH[3]}
WARNING=${BASH_REMATCH[4]}
于 2010-04-25T00:35:03.103 回答
3

内置read命令可以解决问题:

read TMP1 RECORDS TMP2 DELETED TMP3 SKIPPED TMP4 WARNING

更新:您还可以使用set

set $line
RECORDS=$2
DELETED=$4
SKIPPED=$6
WARNING=$8
于 2010-04-24T23:54:03.440 回答
1

这是一个您可以使用的 shell 函数,它只创建许多名称/值对。它假设事情的格式如你所说,但很容易改变:

parseline() {
    while [ $# -ge 2 ] ; do
        eval $(echo $1 | tr -d : | tr '[a-z]' '[A-Z]')="$2"
        shift 2
    done
}

像这样执行它:

$ parseline Records: 2910 Deleted: 0 Skipped: 0 Warnings: 0
$ echo $RECORDS
2910
$ echo $WARNINGS
0
于 2010-04-25T02:45:40.510 回答
0

您可以根据行的结构尝试使用“sed”或“cut”,如下所示:

#!/bin/sh                                                                       

DYNAMIC="Records: 2910 Deleted: 1 Skipped: 2 Warnings: 3"

RECORDS=`echo "$DYNAMIC" | sed 's/.*Records: \([0-9]*\).*/\1/g'`
DELETED=`echo "$DYNAMIC" | sed 's/.*Deleted: \([0-9]*\).*/\1/g'`
SKIPPED=`echo "$DYNAMIC" | sed 's/.*Skipped: \([0-9]*\).*/\1/g'`
WARNINGS=`echo "$DYNAMIC" | sed 's/.*Warnings: \([0-9]*\).*/\1/g'`

echo "Records $RECORDS"
echo "Deleted $DELETED"
echo "Skipped $SKIPPED"
echo "Warnings $WARNINGS"

echo "$DYNAMIC" | cut -d " " -f2
echo "$DYNAMIC" | cut -d " " -f4
echo "$DYNAMIC" | cut -d " " -f6
echo "$DYNAMIC" | cut -d " " -f8
于 2010-04-25T00:03:11.630 回答
0
#!/bin/bash
s="Records: 2910 Deleted: 0 Skipped: 0 Warnings: 0"
s=${s//: /=}
for i in $(printf ${s// /"\n"})
do
 eval $i
done

echo "Records: $Records"
echo "Deleted: $Deleted"
echo "Skipped: $Skipped"
echo "Warnings: $Warnings"

输出

$ ./shell.sh
Records: 2910
Deleted: 0
Skipped: 0
Warnings: 0
于 2010-04-25T03:12:59.097 回答