Sort a text file by line length including spaces

后端 未结 11 2166
故里飘歌
故里飘歌 2020-11-27 11:21

I have a CSV file that looks like this

AS2345,ASDF1232, Mr. Plain Example, 110 Binary ave.,Atlantis,RI,12345,(999)123-5555,1.56
AS2345,ASDF1232, Mrs. Plain Exampl         


        
11条回答
  •  天涯浪人
    2020-11-27 11:33

    The AWK solution from neillb is great if you really want to use awk and it explains why it's a hassle there, but if what you want is to get the job done quickly and don't care what you do it in, one solution is to use Perl's sort() function with a custom caparison routine to iterate over the input lines. Here is a one liner:

    perl -e 'print sort { length($a) <=> length($b) } <>'
    

    You can put this in your pipeline wherever you need it, either receiving STDIN (from cat or a shell redirect) or just give the filename to perl as another argument and let it open the file.

    In my case I needed the longest lines first, so I swapped out $a and $b in the comparison.

提交回复
热议问题