Home > Software design >  Why is this bash command not sorting the data by column 2?
Why is this bash command not sorting the data by column 2?

Time:04-16

Given data file

dogfood    dev        project    virtual-machine      z                  
dogfood    admin      z          dev-center           devcenter           
dogfood    admin      .          machine-definition   machinedefinition   
z          admin      .          network-setting      networksetting      
dogfood    z          .          project              project             
self-host    admin      .          vnet                 vnet                
dogfood    admin      project    z                    pool                
self-host  admin      vnet       subnet               default

$ cat data | sort -k2 returns

z          admin      .          network-setting      networksetting      
dogfood    admin      .          machine-definition   machinedefinition   
self-host    admin      .          vnet                 vnet                
dogfood    admin      project    z                    pool                
dogfood    admin      z          dev-center           devcenter           
dogfood    dev        project    virtual-machine      z                  
dogfood    z          .          project              project             
self-host  admin      vnet       subnet               default

Why is z not at the bottom of column 2?

If I add a few more spaces after one of the "self-host" columns it sorts correctly. I expected to be able to add as many spaces between columns as I wanted, but it actually appears to affect the sort.

CodePudding user response:

       -b, --ignore-leading-blanks
              ignore leading blanks

So this does it!

cat data | sort -b -k2

CodePudding user response:

It appears that your file uses multiple spaces instead of tabs to delimit columns.

Try this:

awk 'BEGIN{OFS="\t"} $1=$1' file | sort -k2 | column -t

Or,

sort -b -k2 file

Either prints:

dogfood    admin  .        machine-definition  machinedefinition
z          admin  .        network-setting     networksetting
self-host  admin  .        vnet                vnet
dogfood    admin  project  z                   pool
self-host  admin  vnet     subnet              default
dogfood    admin  z        dev-center          devcenter
dogfood    dev    project  virtual-machine     z
dogfood    z      .        project             project
  •  Tags:  
  • bash
  • Related