Receiving file lines, and handling them (BASH)

1

I need a bash script that will read a file, recognize the delimiter (in the case ";") and store the values that are in the delimiters in variables, to later build a menu with the dialog ...

What I have done so far is:

#!/bin/bash
file="Tarefas.cfg"
nomeTarefa=''
dirOrigem=''
dirDest=''
tipoBkp=''
agendarBkp=''
compactarBkp=''
gerarLog=''
echo
for linha in $(cat $file)
do
    nomeTarefa=$(echo $linha | cut -d\; -f1 )
    dirOrigem=$(echo $linha | cut -d\; -f2 )
    dirDest=$(echo $linha | cut -d\; -f3 )
    tipoBkp=$(echo $linha | cut -d\; -f4 )
    agendarBkp=$(echo $linha | cut -d\; -f5 )
    compactarBkp=$(echo $linha | cut -d\; -f6 )
    gerarLog=$(echo $linha | cut -d\; -f7 )
    echo "$nomeTarefa $dirOrigem $dirDest $tipoBkp $agendarBkp $compactarBkp $gerarLog"
    echo
done

The file it reads is the following:

Minha Tarefa;/home/;/home/;Diferencial;;N;S;
Minha Tarefa;/home/thalesg;/home/;Diferencial;;N;S;

The output is as follows:

Minha Minha Minha Minha Minha Minha Minha

Tarefa /home/ /home/ Diferencial  N S

Minha Minha Minha Minha Minha Minha Minha

Tarefa /home/thalesg /home/ Diferencial  N S
    
asked by anonymous 31.10.2015 / 22:13

2 answers

1

The code below solved my problem:

#!/bin/bash

file="Tarefas.cfg"
count=0;
declare arrNomeTarefa;
declare arrDirOrigem;
declare arrDirDest;
declare arrTipoBkp;
declare arrAgendarBkp;
declare arrCompactarBkp;
declare arrGerarLog;

function carregaTarefas {
    while IFS=";" read nomeTarefa dirOrigem dirDest tipoBkp agendarBkp compactarBkp gerarLog || [[ -n "$gerarLog" ]]; do #RECEBE NAS VARS OS VALORES DELIMITADOS POR ;
        count=$((count + 1)); #INICIA O COUNT PARA INCREMENTAR O OPTIONS
        options[$count]=$count" $nomeTarefa" #CONCATENA O OPTIONS

        arrNomeTarefa[$count]="$nomeTarefa"
        arrDirOrigem[$count]="$dirOrigem"
        arrDirDest[$count]="$dirDest"
        arrTipoBkp[$count]="$tipoBkp"
        arrAgendarBkp[$count]="$agendarBkp"
        arrCompactarBkp[$count]="$compactarBkp"
        arrGerarLog[$count]="$gerarLog"
    done < $file ##END READ FILE
}

function criaLista {
    options=(${options[@]}) #STRING DINAMICA COM OS NOMES DAS TAREFAS
    cmd=(dialog --keep-tite --menu "Select options:" 22 76 16) #COMANDO DE CRIAÇÃO DA DIALOG
    choices=$("${cmd[@]}" "${options[@]}" 2>&1 >/dev/tty) #EXECUÇÃO DA DIALOG  

}
    
02.11.2015 / 08:34
1

Sorry: this is more a set of comments than an answer ...

As an alternative to what you wrote, I suggested:

  • use of while read var instead of for (because of spaces)
  • use of arrays

(It would probably be best to write such scripts in perl, python, etc.)

#!/bin/bash
file="Tarefas.cfg"    
cat $file | while read linha 
do
  arr=(${linha//;/ })                # split por ";"

  echo "==> ${arr[1]} ${arr[2]} "
done
    
02.11.2015 / 08:22