[awk] How to use awk sort by column 3

I have a file (user.csv)like this

ip,hostname,user,group,encryption,aduser,adattr

want to print all column sort by user,

I tried awk -F ":" '{print|"$3 sort -n"}' user.csv , it doesn't work.

This question is related to awk

The answer is


Seeing as that the original question was on how to use awk and every single one of the first 7 answers use sort instead, and that this is the top hit on Google, here is how to use awk.

Sample net.csv file with headers:

ip,hostname,user,group,encryption,aduser,adattr
192.168.0.1,gw,router,router,-,-,-
192.168.0.2,server,admin,admin,-,-,-
192.168.0.3,ws-03,user,user,-,-,-
192.168.0.4,ws-04,user,user,-,-,-

And sort.awk:

#!/usr/bin/awk -f
# usage: ./sort.awk -v f=FIELD FILE

BEGIN { 
   FS="," 
}

# each line
{ 
   a[NR]=$0 ""
   s[NR]=$f ""  
}

END {
   isort(s,a,NR); 
   for(i=1; i<=NR; i++) print a[i]
}

#insertion sort of A[1..n]
function isort(S, A, n, i, j) {
   for( i=2; i<=n; i++) {
      hs = S[j=i]
      ha = A[j=i]
      while (S[j-1] > hs) { 
         j--; 
         S[j+1] = S[j]
         A[j+1] = A[j] 
      }
      S[j] = hs
      A[j] = ha
   }
}

To use it:

awk sort.awk f=3 < net.csv  # OR 

chmod +x sort.awk
./sort.awk f=3 net.csv

How about just sort.

sort -t, -nk3 user.csv

where

  • -t, - defines your delimiter as ,.

  • -n - gives you numerical sort. Added since you added it in your attempt. If your user field is text only then you dont need it.

  • -k3 - defines the field (key). user is the third field.


try this -

awk '{print $0|"sort -t',' -nk3 "}' user.csv

OR

sort -t',' -nk3 user.csv

awk -F "," '{print $0}' user.csv | sort -nk3 -t ','

This should work


  1. Use awk to put the user ID in front.
  2. Sort
  3. Use sed to remove the duplicate user ID, assuming user IDs do not contain any spaces.

    awk -F, '{ print $3, $0 }' user.csv | sort | sed 's/^.* //'
    

awk -F, '{ print $3, $0 }' user.csv | sort -nk2 

and for reverse order

awk -F, '{ print $3, $0 }' user.csv | sort -nrk2 

You can choose a delimiter, in this case I chose a colon and printed the column number one, sorting by alphabetical order:

awk -F\: '{print $1|"sort -u"}' /etc/passwd

To exclude the first line (header) from sorting, I split it out into two buffers.

df | awk 'BEGIN{header=""; $body=""} { if(NR==1){header=$0}else{body=body"\n"$0}} END{print header; print body|"sort -nk3"}'