简体   繁体   English

通过shell,awk,bash排序?

[英]Sorting through shell, awk, bash?

I am trying to learn bash/shell *nix commands /scripting. 我正在尝试学习bash / shell * nix命令/脚本。 So rather than writing a python program, I thought of trying it out using bash/awk etc but am having a hard time. 因此,除了编写python程序外,我还想使用bash / awk等进行尝试,但遇到了麻烦。 I have a huge text (its actually csv )file 我有一个很大的文本(实际上是csv)文件

 id_1, id_2, some attributes.

I want to sort this file based on id2? 我想根据id2对该文件排序? how do i do this? 我该怎么做呢? Thanks 谢谢

Use the --key option for sort . 使用--key选项进行sort

For example, the following sorts input.csv on the second field (using comma as a field separator) and writes the output to output.csv . 例如,以下input.csv在第二个字段上对input.csv进行排序(使用逗号作为字段分隔符),并将输出写入output.csv

 sort --key=2,2 -t',' input.csv > output.csv

ps Don't forget to use the -n option if you're doing a numerical sort. ps如果要进行数字排序,请不要忘记使用-n选项。

For more info, see the man page for sort . 有关更多信息,请参见手册页进行排序

You can use -k option of sort(1) 您可以使用sort(1)的 -k选项

-k, --key=POS1[,POS2] -k,--key = POS1 [,POS2]

  start a key at POS1, end it at POS2 (origin 1) 
sort -t, -k2 filename.csv

我没有要验证的外壳,但是基本上您需要指定分隔符和排序键

checkout the command cut: 签出命令剪切:

cat file.cvs | cut -d";" -f 2 | sort

I assumed your csv is semi-colon separated, but you can change it. 我假设您的csv是用分号分隔的,但是您可以更改它。

Save into a different name: 保存为其他名称:

cat file.cvs | cut -d";" -f 2 | sort > newfile.txt

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM