![행을 CSV 파일로 변환하는 명령](https://linux55.com/image/157270/%ED%96%89%EC%9D%84%20CSV%20%ED%8C%8C%EC%9D%BC%EB%A1%9C%20%EB%B3%80%ED%99%98%ED%95%98%EB%8A%94%20%EB%AA%85%EB%A0%B9.png)
각 줄 앞에 공백이 있는 다음 형식의 파일이 있습니다.
"Western Overseas",
"Western Overseas",
"^",
"--",
"^",
"--",
"--",
null,
24995,
9977,
"CR",
"Western Refrigeration Private Limited",
"Western Refrigeration Private Limited",
"[ICRA]A",
"--",
"[ICRA]A1",
"--",
"Stable",
null,
14951,
2346,
"CR",
다음 형식의 CSV 파일로 변환하고 싶습니다.
"Western Overseas","Western Overseas","^","--","^","--","--",null,24995,9977,"CR"
"Western Refrigeration Private Limited","Western Refrigeration Private Limited","[ICRA]A","--","[ICRA]A1","--","Stable",null,14951,2346,"CR"
사용하려고 하는데 tr
모든 출력을 한 줄로 인쇄하고 줄 바꿈을 이중 줄 바꿈으로 바꾸는 것 같아서 문제가 있습니다. 도움을 주시면 감사하겠습니다.
답변1
awk의 해결책은 다음과 같습니다.
awk '{if(NF){gsub(/^ |,$/,""); printf c $0; c=","}else{printf "\n"; c=""}};END{printf "\n"}'
확장된 설명:
{
if(NF) { # if the line isn't empty
gsub(/^ |,$/,""); # remove the first space and last comma
printf c $0; # print the line (without a newline)
c="," # set c to add a comma for the next field
} else {
printf "\n"; # empty line, output a newline
c="" # don't print a comma for the next entry
}
};
END {
printf "\n" # finish off with a newline
}
답변2
<file sed '
:start
s/\n$//
t
s/\n //
N
b start
' | sed 's/,$//'
첫 번째는 마지막 개행 문자를 찾아서 제거할 때까지( ) 루프를 반복하고 sed
( :start
, b start
) 패턴 공간( )에 줄을 추가합니다 . 이는 빈 줄을 읽은 다음 도구가 루프를 종료했음을 의미합니다( ). 각 반복에서 남아 있는 줄 바꿈(및 연속 공백)은 줄을 연결하기 위해 제거됩니다( ).N
s/\n$//
t
s/\n //
두 번째는 sed
후행 쉼표를 제거합니다.