bash 如何在 Linux 上使用不同的工作表创建 CSV 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26697989/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 11:41:06  来源:igfitidea点击:

how to create CSV file on Linux with different sheets

linuxbashcsvawksed

提问by maihabunash

it easy on Linux to create CSV file as:

在 Linux 上很容易将 CSV 文件创建为:

   echo names,OBAMA,PUTIN,KAMERUN > NAMES.csv

it will create CSV file ( sheet 1 )

它将创建 CSV 文件(工作表 1)

but is it possible to create second or third or more sheets in the CSV file?

但是是否可以在 CSV 文件中创建第二个或第三个或更多个工作表?

for example ( I want to create now second sheet - sheet 2 )

例如(我现在想创建第二张表 - 表 2)

   echo best_air_force,USA,RUSSIA,ENGLAND > NAMES.csv

remark - I use bash scripts on my linux machine

备注 - 我在我的 linux 机器上使用 bash 脚本

回答by duskwuff -inactive-

You can't. The CSV file format doesn't provide support for multiple sheets.

你不能。CSV 文件格式不支持多张工作表。

回答by Ed Morton

The answer depends on what tool you are going to use to display/edit the file as separate sheets. For example, you could create a CSV file like:

答案取决于您将使用什么工具将文件显示/编辑为单独的工作表。例如,您可以创建一个 CSV 文件,如:

a,b,c
-
d,e,f

and then you can use a script like this (GNU awk for multi-char RS):

然后您可以使用这样的脚本(用于多字符 RS 的 GNU awk):

awk -v sheet=<number> -v RS='(^|\n)-\n|\n$' 'NR==sheet' file

to select sheets:

选择工作表:

$ awk -v sheet=1 -v RS='(^|\n)-\n|\n$' 'NR==sheet' file
a,b,c
$ awk -v sheet=2 -v RS='(^|\n)-\n|\n$' 'NR==sheet' file
d,e,f

Since there is no one spec for "CSV" you could still say this is "CSV" but in this case I'd name the tool you use to view it as separate sheets something like "foo" and use ".foo" instead of "csv" as the suffix. Like MS does with "Excel" and ".xls".

由于“CSV”没有一个规范,您仍然可以说这是“CSV”,但在这种情况下,我会将您用来查看它的工具命名为“foo”之类的单独工作表,并使用“.foo”代替“csv”作为后缀。就像 MS 对“Excel”和“.xls”所做的那样。

You can use any sequence of characters you like with as many fields as you liek to indicate the sheet-separator, e.g.:

您可以使用任何您喜欢的字符序列和尽可能多的字段来指示工作表分隔符,例如:

-,-,-

<control-char>,<control-char>,<control-char>
END OF SHEET

That second one above is a blank line. The point is the separation into sheets only makes sense in the context of whatever tool you use to display/edit those sheets and you are in complete control of what the separator is since you'll be writing the tool that uses it. It just has to be some string that you know cannot appear naturally in the rest of your file.

上面的第二个是一个空行。关键是将工作表分成工作表仅在您用于显示/编辑这些工作表的任何工具的上下文中才有意义,并且您可以完全控制分隔符是什么,因为您将编写使用它的工具。它只需要是一些您知道不能在文件的其余部分自然出现的字符串。