Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use awk sort by column 3

Tags:

awk

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.

like image 874
user2452340 Avatar asked Jun 11 '13 15:06

user2452340


People also ask

How do you sort data in awk?

The asorti() function One of the functions introduced in GNU awk, asorti(), provides the ability to sort an array by key (or index) or value. You can only sort the array once it has been populated, meaning that this action must not occur with every new record but only the final stage of your script.

How do I sort a column in Linux?

Use the -k option to sort on a certain column. For example, use “-k 2” to sort on the second column.


2 Answers

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.

like image 111
jaypal singh Avatar answered Sep 19 '22 13:09

jaypal singh


  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/^.* //' 
like image 25
user3781670 Avatar answered Sep 21 '22 13:09

user3781670