Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/unix/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Unix 如何使用bash获取大文件中每个组中的前x行_Unix_Awk_Sed - Fatal编程技术网

Unix 如何使用bash获取大文件中每个组中的前x行

Unix 如何使用bash获取大文件中每个组中的前x行,unix,awk,sed,Unix,Awk,Sed,我使用的是bash3.2.53。我不能使用sql。sed、awk优先 我有一个巨大的数据文件,有1亿行。每行有3列=>word1、word2和count。它们按单词1(升序)和计数(降序)的顺序排列。我需要前3行的每个唯一的字1连同计数。如果一个单词有

我使用的是bash3.2.53。我不能使用sql。sed、awk优先

我有一个巨大的数据文件,有1亿行。每行有3列=>word1、word2和count。它们按单词1(升序)和计数(降序)的顺序排列。我需要前3行的每个唯一的字1连同计数。如果一个单词有<3行,那么我需要该单词的所有行

示例文件:

acceleration in 26
acceleration of 18
accent and 104
accent i 62
accent is 61
accent the 51
accent in 37
accented with 90
accented by 25
accented the 11
accented and 2
accented english 2
acceleration in 26
acceleration of 18
accent and 104
accent i 62
accent is 61
accented with 90
accented by 25
accented the 11
我想要的输出:

acceleration in 26
acceleration of 18
accent and 104
accent i 62
accent is 61
accent the 51
accent in 37
accented with 90
accented by 25
accented the 11
accented and 2
accented english 2
acceleration in 26
acceleration of 18
accent and 104
accent i 62
accent is 61
accented with 90
accented by 25
accented the 11

假设输入已排序,则以下操作应有效

awk 'word!=$1{count=1;word=$1} count<=3{print; count++}'
当计数小于或等于3时,打印行和增量计数:

count<=3{print; count++}

countawk'单词=$1$2{count=1;word=$1$2}countEtan-谢谢你修改了格式。你救了我一天。多谢。它就像一个符咒。伊坦,我正在做类似的事情,但无法让它发挥作用。我的awk很弱。我有一个类似的场景,但现在我有3个单词和一个计数。前两个单词按升序排列,计数按降序排列。我需要前2个单词的前3行。我用word1+word2创建了一个新的专栏,然后使用您的脚本,它就可以工作了。但是试着看看是否有任何很酷的awk脚本可以做同样的事情。谢谢你的话=$1$2{count=1;word=1$2}count@Viswa这是一个正确的想法,尽管您可能希望在其中插入一个分隔符(比如
subsp
,它不太可能出现在您的任何单词中),以防止两个小词相当于一个较长的词(不太可能,尤其是在这种情况下,但通常值得注意).谢谢Etan的提示。太棒了,你回答了你自己的问题。请友好一点,并添加一些额外的解释,说明此解决方案与其他答案的不同之处,以及它的作用–这样其他读者也可以从您的答案中获益。如果你认为自己的答案比其他答案更有帮助,那么在2天内你应该能够接受自己的答案。