use*_*513 3 osx shell-script text-processing text-formatting
我有一个以下格式的文件,每行前都有一个前导空格:
"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",
Run Code Online (Sandbox Code Playgroud)
我想将其转换为 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"
Run Code Online (Sandbox Code Playgroud)
我正在尝试使用,tr但遇到了麻烦,因为它将所有输出打印到一行,并且似乎用双换行符替换换行符。任何帮助表示赞赏。
小智 5
awk 的解决方案是
awk '{if(NF){gsub(/^ |,$/,""); printf c $0; c=","}else{printf "\n"; c=""}};END{printf "\n"}'
Run Code Online (Sandbox Code Playgroud)
扩展了评论:
{
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
}
Run Code Online (Sandbox Code Playgroud)