
쉼표로 구분된 파일을 반복하는 방법은 무엇입니까?
나는 다음을 시도했다:
$ cat file | tr ',' '\n' > /tmp/f1
$ while read -r line;do
echo $line;
done < /tmp/f1
임시 파일을 만들지 않고 콘텐츠의 첫 번째 줄을 반복하려면 어떻게 해야 합니까?
어떤 아이디어가 있나요?
답변1
첫 번째,텍스트 구문 분석에 셸 루프를 사용하지 마세요.. 이는 수행하기 어렵고 오류가 발생하기 쉬우며 읽기도 어렵습니다. 그리고 매우 느립니다. 매우 매우 느립니다. 대신 awk
"필드"에서 읽을 수 있도록 특별히 설계된 것을 사용하십시오. 예를 들어 다음 입력 파일을 사용합니다.
foo, bar, baz
oof, rab, zab
awk -F,
필드 구분 기호를 다음과 같이 설정하여 쉼표로 구분된 각 필드를 읽을 수 있습니다 ,
.
$ 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
쉘에서 이 작업을 고집하더라도 임시 파일이 필요하지 않습니다 tr
. while read
쉼표로 구분할 수 있습니다.
$ 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
답변2
csv 파일의 필드는 여러 줄에 걸쳐 있을 수 있습니다. 이것이 바로 제가 사용하는 것을 선호하는 이유입니다.xsvcsv를 구문 분석해야 할 때.
bash 및 xsv를 사용하여 csv 파일을 구문 분석하는 한 가지 방법은 다음과 같습니다.
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