1


我需要将特定行的编号设置为变量。
在这种情况下:生成的文档(rsync)中有这样一行:

传输的文件数:23

var1=`grep -E '\<Number of files transferred: [0-9]+\>' /path/to/document.txt`<br>

让我接电话。

echo $var1 | egrep -o "[0-9]+"

给我看 23
我需要一种(好的)方法来获取变量中的数字。

谢谢!

4

3 回答 3

1

使用命令替换

number=$(echo $var1 | egrep -o "[0-9]+")

该变量number现在应该具有命令的输出echo $var1 | egrep -o "[0-9]+"


如果你grep支持 PCRE,你可以说:

number=$(grep -oP '\bNumber of files transferred: \K[0-9]+\b' /path/to/document.txt)
于 2013-10-30T07:39:41.463 回答
0

Three alternative approaches:

  1. You can use the ${WORD##PATTERN} parameter expansion feature in bash to extract the number:

    RSYNC=/path/to/document.txt
    TRANSFERRED=$(grep -E '^Number of files transferred: [0-9]+$' -- "$RSYNC")
    FILE_COUNT=${TRANSFERRED##*: }
    
  2. Use $IFS (the input field separator) together with the read command and a here string:

    IFS=: read _ FILE_COUNT <<<"$TRANSFERRED"
    
  3. Use sed instead of grep, as suggested by wich in another answer, but since OS X has a BSD-ish version of sed, you will need to write the command like this:

    COMMAND='s/^Number of files transferred: \([0-9]\{1,\}\)$/\1/p'
    FILE_COUNT=$(sed -n -e "$COMMAND" -- "$RSYNC")
    

But, I think an important question to ask is, why are you storing the output of rsync in a file? Do you really need to keep it? If not, then you could pipe the output of rsync into a subshell that does whatever processing you need to do. For example, you could do this kind of thing:

rsync --stats ... | {
    FILE_COUNT=unknown
    TOTAL_SIZE=unknown
    while IFS=: read KEY VALUE; do
        case "$KEY" in
            Number of files transferred) FILE_COUNT=$VALUE ;;
            Total file size) TOTAL_SIZE=$VALUE ;;
        esac
    done
    case "$FILE_COUNT" in
        1) echo "$FILE_COUNT file ($TOTAL_SIZE bytes) was transferred."
        *) echo "$FILE_COUNT files ($TOTAL_SIZE bytes) were transferred."
    esac
}
于 2013-10-30T09:50:22.147 回答
0

如果您知道前缀的长度,只需选择一个子字符串。

var1=${var1:29}

或者,用不同的方法代替 grep

var1=$(sed -n -e '/.*\<Number of files transferred: ([0-9]\+)\>.*/\1/p' < /path/to/document.txt)
于 2013-10-30T07:41:31.203 回答