简体   繁体   English

如何“反转”输出bash

[英]how to “reverse” the output bash

I have an output that looks like this: (number of occurrences of the word, and the word) 我有一个看起来像这样的输出:(单词的出现次数和单词)

    3 I
    2 come
    2 from
    1 Slovenia

But I want that it looked like this: 但我希望它看起来像这样:

I 3
come 2
from 2
Slovenia 1

I got my output with: 我得到了我的输出:

cut -d' ' -f1 "file" | uniq -c | sort -nr

I tried to do different things, with another pipes: 我尝试用另一个管子做不同的事情:

 cut -d' ' -f1 "file" | uniq -c | sort -nr | cut -d' ' -f8 ...?

which is a good start, because I have the words on the first place..buuut I have no access to the number of occurrences? 这是一个好的开始,因为我在第一个地方有这个词。但是我没有访问次数?

AWK and SED are not allowed! AWK和SED是不允许的!

EDIT: alright lets say the file looks like this. 编辑:好吧,让我们说文件看起来像这样。

I ....
come ...
from ... 
Slovenia ...
I ...
I ....
come ...
from ....

I is repeated 3 times, come twice, from twice, Slovenia once. 我重复了3次,两次,两次,斯洛文尼亚一次。 +They are on beginning of each line. +他们在每一行的开头。

AWK and SED are not allowed! AWK和SED是不允许的!

Starting with this: 从这开始:

$ cat file
    3 I
    2 come
    2 from
    1 Slovenia

The order can be reversed with this: 订单可以通过以下方式撤消:

$ while read count word; do echo "$word $count"; done <file
I 3
come 2
from 2
Slovenia 1

Complete pipeline 完整的管道

Let us start with: 让我们从:

$ cat file2
I ....
come ...
from ... 
Slovenia ...
I ...
I ....
come ...
from ....

Using your pipeline (with two changes) combined with the while loop: 使用您的管道(有两个更改)与while循环结合使用:

$ cut -d' ' -f1 "file2" | sort | uniq -c | sort -snr | while read count word; do echo "$word $count"; done 
I 3
come 2
from 2
Slovenia 1

The one change that I made to the pipeline was to put a sort before uniq -c . 我对管道做的一个改变是在uniq -c之前进行sort This is because uniq -c assumes that its input is sorted. 这是因为uniq -c假定其输入已排序。 The second change is to add the -s option to the second sort so that the alphabetical order of the words with the same count is not lost 第二个更改是将-s选项添加到第二个排序,以便具有相同计数的单词的字母顺序不会丢失

You can just pipe an awk after your first try: 你可以在第一次尝试后输出一个awk

$ cat so.txt
    3 I
    2 come
    2 from
    1 Slovenia

$ cat so.txt | awk '{ print $2 " " $1}'
I 3
come 2
from 2
Slovenia 1

If perl is allowed: 如果允许perl:

$ cat testfile
I ....
come ...
from ... 
Slovenia ...
I ...
I ....
come ...
from ....

$ perl -e 'my %list;
           while(<>){
              chomp; #strip \n from the end
              s/^ *([^ ]*).*/$1/; #keep only 1st word
              $list{$_}++; #increment count
           }
           foreach (keys %list){
               print "$_ $list{$_}\n";
           }' < testfile

come 2
Slovenia 1
I 3
from 2

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

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