解析 shell 数组中的 cut-delim 文本

Parsing a cut-delim text in shell arrays

我想解析一个带分隔符的 txt 文件并将其分配给一个数组。

示例文本文件如下所示:

create_tetro.c:132://   printf("\t\t\tSol %d found !\n", sol);
float_to_int.c:23://    printf("%f -> %d\n", i, ((int)i / 1) + 0.9999);
free_all.c:19:  printf("update_pieces\n");

所有 .gres*.txt 都是完全相同的文件,但我没有找到一种只在一个循环中执行此操作的方法。然而,当我尝试 echo ${array[2]} 时,它只显示空白。 到目前为止想出了这个:

#!/bin/bash

IFS='\n'
i=0

typeset -a file
typeset -a line_nb=()
typeset -a string=()

while read line; do
{
file[i]="$(cut -d ':' -f1)"
((i++))
}
done < .gres.txt

while read line; do
line_nb[$i]="$(cut -d ':' -f2)";
let i=i+1;
done < .gres2.txt

while read line; do
string[i]="$(cut -d ':' -f3)"
let "i++"
done < .gres3.txt

不完全确定您需要什么,但现在 cut 不会做太多事情,每个数组都从一个索引开始。你可能会得到更好的结果:

    #!/bin/bash

    i=0

    while read line; do
    {
    file[$i]="$(cut -d ':' -f1 <<< $line)"
    line_nb[$i]="$(cut -d ':' -f2 <<< $line)"
    string[$i]="$(cut -d ':' -f3 <<< $line)"
    ((i++))
    }
    done < ./gres.txt

希望能帮到你