简体   繁体   English

如何在bash中对文本文件的行进行块排序?

[英]How to block-sort rows of text file in bash?

I have a bar-separated text file that looks like this: 我有一个用竖线分隔的文本文件,如下所示:

stringC|rest-of-lineC3
stringC|rest-of-lineC1
stringC|rest-of-lineC2
stringA|rest-of-lineA2
stringA|rest-of-lineA1
stringB|rest-of-lineB4
stringB|rest-of-lineB1
stringB|rest-of-lineB3
stringB|rest-of-lineB2

I need to block-sort it by the string before the | 我需要按|之前的字符串对它进行块排序| without doing secondary sort of what comes after the bar. 无需再进行诸如此类的后续操作。 So the example below SHOULD be sorted into: 因此,以下示例应分类为:

stringA|rest-of-lineA2
stringA|rest-of-lineA1
stringB|rest-of-lineB4
stringB|rest-of-lineB1
stringB|rest-of-lineB3
stringB|rest-of-lineB2
stringC|rest-of-lineC3
stringC|rest-of-lineC1
stringC|rest-of-lineC2

but NOT into: 但不能进入:

stringA|rest-of-lineA1
stringA|rest-of-lineA2
stringB|rest-of-lineB1
...

Is there a way of doing this in a bash script using sort or any other commands? 在bash脚本中是否可以使用sort或任何其他命令来执行此操作?

How can I get the same result as above in case the original file is not in blocks, ie it looks something like this: 万一原始文件不在块中,那么我如何获得与上述相同的结果,即它看起来像这样:

stringC|rest-of-lineC3
stringA|rest-of-lineA2
stringC|rest-of-lineC1
stringA|rest-of-lineA1
stringB|rest-of-lineB4
stringB|rest-of-lineB1
stringC|rest-of-lineC2
stringB|rest-of-lineB3
stringB|rest-of-lineB2

sort with -s option for stable 使用-s选项进行排序以保持稳定

sort -st'|' -k1,1 file

initial blocks doesn't matter, should work for both. 初始块无关紧要,应该对两者都起作用。

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

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