需要读取文件并将结果用作shell脚本中的命名变量

时间:2017-12-08 11:35:42

标签: linux bash shell

我有一个来自venn程序的输出文件。

[1, 2],106
[1, 3],2556
[2, 3],5207
[1, 2, 3],232
[2],7566
[3],8840
[1],5320

我需要一个命令来将每个行结果号作为变量参数在这样的脚本中获取:

$area1=here it must come the results after [1],
$area2=here it must come the results after [2],
$area3=here it must come the results after [3],
$n12=here it must come the results after [1, 2],
$n13=here it must come the results after [1, 3],
$n23=here it must come the results after [2, 3],
$n123=here it must come the results after [1, 2, 3],

然后将在下面的脚本中使用这些结果来绘制维恩图。

cat << catfile >> $prefix1-VennDiagram.R
library(VennDiagram);
venn.diagram(
    x = list(
        "$sample1" = c(1:$area1, $(($area1+1)):$(($area1+$n12)), $(($area1+$n12+1)):$(($area1+$n12+$n123)), $(($area1+$n12+$n123+1)):$(($area1+$n12+$n123+$n13))),
        "$sample2" = c($(($area1+$n12+$n123+$n13+1)):$(($area1+$n12+$n123+$n13+$area2)), $(($area1+1)):$(($area1+$n12)), $(($area1+$n12+1)):$(($area1+$n12+$n123)), $(($area1+$n12+$n123+$n13+$area2+1)):$(($area1+$n12+$n123+$n13+$area2+$n23))),
        "$sample3" = c($(($area1+$n12+$n123+$n13+$area2+$n23+1)):$(($area1+$n12+$n123+$n13+$area2+$n23+$area3)),  $(($area1+$n12+1)):$(($area1+$n12+$n123)), $(($area1+$n12+$n123+1)):$(($area1+$n12+$n123+$n13)), $(($area1+$n12+$n123+$n13+$area2+1)):$(($area1+$n12+$n123+$n13+$area2+$n23)))
        ),
    filename = "$prefix1-VennDiagram.tiff",
    col = "transparent",
    fill = c("red", "blue", "green"),
    alpha = 0.5,
    label.col = c("darkred", "white", "darkblue", "white", "white", "white", "darkgreen"),
    cex = 2.5,
    fontfamily = "arial",
    fontface = "bold",
    cat.default.pos = "text",
    cat.col = c("darkred", "darkblue", "darkgreen"),
    cat.cex = 2.0,
    cat.fontfamily = "arial",
    cat.fontface = "italic",
    cat.dist = c(0.06, 0.06, 0.03),
    cat.pos = 0
    );
catfile

Rscript $prefix1-VennDiagram.R
exit

1 个答案:

答案 0 :(得分:0)

在BASH中,首先将值存储在关联数组中然后将它们分配给正确的变量会很方便。

假设venn的输出存储在venn.txt中 然后以下代码可以为您解析

declare -A venn
while read line ; do 
   key=$(echo "$line" | sed 's/^\(\[[^]]*\]\).*/\1/') 
   value=$(echo "$line" | sed 's/^\[[^]]*\],\(.*\)/\1/') 
   if [ -n "$key" ] ; then # This check is necessary 
                           # to protect against empty lines
     venn["$key"]="$value" ; 
   fi 
done <<< "$( cat venn.txt )"

现在您可以从脚本中的数组中提取变量

area1=${venn["[1]"]}
area2=${venn["[2]"]}
area3=${venn["[3]"]}
n12=${venn["[1, 2]"]}
n13=${venn["[1, 3]"]}
n23=${venn["[2, 3]"]}
n123=${venn["[1, 2, 3]"]}

在解析代码中,我们使用Here String <<<word语法,以便在与其余代码相同的shell实例中执行循环,以便记录对关联数组的更改。