【问题标题】:Setting A Variable in A While Loop in Bash在 Bash 的 While 循环中设置变量
【发布时间】:2014-03-02 14:12:17
【问题描述】:

我需要帮助将下面 grep 命令的输出设置为每行的变量。

    while read line; do 
        grep -oP '@\K[^ ]*' <<< $line
    done < tweets

上面显示了我想要的内容:

月光宝

Mags_GB

等等……

但是,如果我会这样做:

    while read line; do
        usrs="grep -oP '@\K[^ ]*' <<< $line"
    done < tweets

    echo $usrs

它显示奇怪的结果,当然不是我正在寻找的结果。我需要 $usrs 来显示我上面提到的内容。示例:

月光宝

Mags_GB

【问题讨论】:

标签: string bash variables loops grep


【解决方案1】:

像这样使用 BASH 数组和 command substitution

users=()
while read -r line; do
    users+=( "$(grep -oP '@\K[^ ]*' <<< "$line")" )
done < tweets

或者使用process substitution:

users=()
while read -r line; do
    users+=( "$line" )
done < <(grep -oP '@\K[^ ]*' tweets)

printf "%s\n" "${users[@]}"

【讨论】:

    【解决方案2】:

    根本不需要循环。 grep 无论如何都会遍历输入的行:

    usrs=$(grep -oP '@\K[^ ]*' tweets)
    

    【讨论】:

    • 这几乎显示了我想要的,但输出没有显示在自己的行上。每个单词都需要在自己的行中。有什么想法吗?
    • @RydallCooper 在打印变量时使用引号:echo "$usrs"
    • @RydallCooper:如果你只想要输出,grep -oP '@\K[^ ]*' tweets 就是你所需要的。如果您想对输出进行进一步处理,请告诉我们您要执行的操作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-29
    • 2011-06-02
    • 2016-09-13
    • 2019-01-05
    • 2014-03-31
    相关资源
    最近更新 更多