在循环中创建新的shell变量

时间:2015-12-07 19:52:30

标签: shell

通过这里的一些帮助,我只得到文件中的引号之间的文字,如下所示:

text undefined but text
something something text something
        shouldfindthis "dolphin"
        butalsothis "elephant"

做:

i=0
regex='(".*?")' # Match all what is between "
while read line # read file line by line      
do           
    if [[ $line =~ $regex ]]; then # If regex match
        vars[$i]="${BASH_REMATCH[1]}" # store capturing group in a array
        i=$((i + 1))
    fi
done < txt # file "txt"

# Print what we found
if [ -v "vars" ]; then # if we found something , "vars" will exist
    for var in "${vars[@]}" 
    do
      echo "$var"
    done
fi

产生输出:

$ ./script.sh 
"dolphin"
"elephant"

有没有办法将这些标记为变量?因此,海豚是$ text1,大象是$ text2?这样做,我只能替换paranthasis中的文本?

1 个答案:

答案 0 :(得分:1)

首先:正如您的代码所做的那样,使用数组是最佳实践方法。不要改变它。但是,如果确实想要写入单独的变量而不是数组,那么请替换:

vars[$i]="${BASH_REMATCH[1]}" # this could also be vars+=( "${BASH_REMATCH[1]}" )

...与...

printf -v "text$i" '%s' "${BASH_REMATCH[1]}"

如果您想自己删除引号,请将它们移到正则表达式中的分组运算符之外:

regex='"([^"]*)"'