Search code examples
arraysstringbashshellline

Parsing a cut-delim text in shell arrays


I want to parse a txt file with delimiters and assign it to an array.

Sample text file looks like:

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");

All .gres*.txt are the exact same files but I didn't find a way to do it only in one loop. Yet, when I try echo ${array[2]}, it just shows me blank. Came up with this so far:

#!/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

Solution

  • Not totally sure about what you need, but right now, cut won't do much and each array starts at an index after the other. You might have a better result with something like that :

        #!/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
    

    Hope it could help