
Como iterar um arquivo que possui vírgula separada por valor?
Eu tentei o seguinte:
$ cat file | tr ',' '\n' > /tmp/f1
$ while read -r line;do
echo $line;
done < /tmp/f1
Como posso iterar o conteúdo da primeira linha sem a criação de um arquivo temporário?
Alguma ideia?
Responder1
Em primeiro lugar,evite fazer análise de texto com loops de shell. É difícil de fazer, fácil de errar e muito difícil de ler. E lento. Muito, muito, lento. Em vez disso, use algo parecido com awk
o que foi projetado especificamente para leitura por "campos". Por exemplo, com este arquivo de entrada:
foo, bar, baz
oof, rab, zab
Você pode ler cada campo separado por vírgula usando awk -F,
para definir o separador de campo como ,
:
$ awk -F, '{ print "The 1st field is",$1,"the 2nd", $2,"and the 3rd", $3}' file
The 1st field is foo the 2nd bar and the 3rd baz
The 1st field is oof the 2nd rab and the 3rd zab
Mesmo se você insistir em fazer isso no shell, você não precisa do arquivo temporário e não precisa do arquivo tr
. Você pode while read
separar por vírgulas:
$ while IFS=, read -r one two three; do
echo "The 1st field is $one, the 2nd $two and the 3rd $three";
done < file
The 1st field is foo, the 2nd bar and the 3rd baz
The 1st field is oof, the 2nd rab and the 3rd zab
Responder2
Os campos em um arquivo csv podem abranger várias linhas, por esse motivo e outros, é por isso que preferi usarxsvquando tive que analisar csv.
Uma maneira de analisar um arquivo csv com bash e xsv pode ser:
csvFile="myfile.csv"
lengthItems=$((($(xsv count "$csvFile") - 1 ))) # -1 because for loop start at 0
for i in $( seq 0 "$lengthItems" ); do
row="$(xsv slice -i "$i" "$csvFile")" # real magic happening here
# Do what you want with your $row here
done