0

I need a script in bash that reads a file and recognize an delimiter (";") and store the values between the delimiters into variables to build a dialog menu later.

What i've done:

#!/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 that it reads is :

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

And the output:

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

1 Answer 1

3

With a while you can split a line into a lot of vars in 1 call.
You need to temporary change the FieldSep (IFS) into a ;
And avoid an extra call to cat: do not use cat $file | .. but use < $file

file="Tarefas.cfg"
while IFS=";" read nomeTarefa dirOrigem dirDest tipoBkp agendarBkp compactarBkp gerarLog; do
   echo "$nomeTarefa $dirOrigem $dirDest $tipoBkp $agendarBkp $compactarBkp $gerarLog"
   echo "Show one field, the compactarBkp: $compactarBkp"
done < $file
Sign up to request clarification or add additional context in comments.

5 Comments

Thank you very much, sir! ---edit--- When I tried with another file with more lines, it didnt show the last line, any ideas why?
Found a solution! Added || [[ -n "$line" ]] after gerarLog
@Tiaurls If you needed that then your file didn't end with a newline. Normally you only need that when you pick an alternate delimiter (like \0, with -d '').
@Etan Reisner Actuallym, i use the echo vars >>Tarefas.cfg I dont know how to create a new line using this, thank you anyway!
@Tiaurls You use what? echo adds a newline at the end of what it prints by default. So if you only ever used echo to write the config file then it should have had a newline at the end.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.