Bash:按前 4 列对 csv 文件进行排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11934809/
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 02:59:56  来源:igfitidea点击:

Bash: sort csv file by first 4 columns

bashshellsortingcsv

提问by Ricky Robinson

I have a csv file with fields delimited by ";". There are 8 fields, and I want to sort my data by the first 4 columns, in increasing order (first sort by column 1, then column 2, etc)

我有一个 csv 文件,其中的字段以“;”分隔。有 8 个字段,我想按前 4 列按升序对数据进行排序(首先按第 1 列排序,然后按第 2 列排序,以此类推)

How I can do this from a command line in linux?

我如何从 linux 的命令行执行此操作?

I tried with open office, but it only lets me select 3 columns.

我尝试使用开放式办公室,但它只能让我选择 3 列。

EDIT: among the fields on which I want to sort my data, three fields contain strings with numerical values, one only strings. How can I specify this with the sortcommand?

编辑:在我想对数据进行排序的字段中,三个字段包含带有数值的字符串,一个只有字符串。如何使用sort命令指定它?

回答by Vijay

Try:

尝试:

sort -t\; -k 1,1n -k 2,2n -k 3,3n -k 4,4n test.txt

eg:

例如:

1;2;100;4
1;2;3;4
10;1;2;3
9;1;2;3

> sort -t\; -k 1,1n -k 2,2n -k 3,3n -k 4,4n temp3
1;2;3;4
1;2;100;4
9;1;2;3
10;1;2;3

回答by Brian Agnew

sort -kwill allow you to define the sort key. From man sort:

sort -k将允许您定义排序键。来自man sort

-k, --key=POS1[,POS2]
       start a key at POS1 (origin 1), end it at POS2 (default end of line). 

So

所以

$ sort -t\; -k1,4

should do it. Note that I've escaped the semi-colon, otherwise the shell will interpret it as an end-of-statement.

应该这样做。请注意,我已经对分号进行了转义,否则 shell 会将其解释为语句结束。