Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I have a file with next format

2011-12-01 user1 access1
2011-12-01 user1 access2
2011-12-01 user2 access2
2011-12-01 user4 access2
2011-12-02 user1 access1
2012-01-01 user3 access1
2012-01-01 user4 access2

I would like to have an output that for every user shows the last date, so

2011-12-02 user1 access1
2011-12-01 user1 access2
2011-12-01 user2 access2
2012-01-01 user3 access1
2012-01-01 user4 access2

I tried something like this:

less myfile.txt | sort -k1r | uniq -f 1  | sort -b -k1

but it isn't seems to work right.

Thank you for help!

share|improve this question
2  
Step 0: you want cat, not less. Somebody will now surely point out that cat myfile | sort is worse than sort myfile, but I find it easier when having long pipe sequences. –  Ulrich Schwarz Jan 25 '12 at 12:42
1  
@UlrichSchwarz <myfile sort | uniq | sort keeps the logical order while not introducing a spurious process. –  Gilles Jan 25 '12 at 23:20

3 Answers 3

up vote 5 down vote accepted

I think you want

cat myfile.txt| sort -k1 -r | sort --unique --stable -k2,3

(see my comment regarding cat above). The first sort will put the newest dates to the top. The second sort will sort by user+access, but, by giving --stable, will keep the previous order of lines that have the same user+access combination, i.e. newest still on top. Giving --unique, only the first line of a run with equal user+access combination is shown. (You can replace it with | uniq -f1, I'd think, if it happens to be a GNU extension your sort doesn't have.)

share|improve this answer
    
Thank you, it works! –  gakhov Jan 25 '12 at 13:19

If you want to do it just with a single call to awk

awk '($1 > a[$2,$3]){a[$2,$3]=$1}END{for(x in a){split(x,b,SUBSEP);print a[x],b[1],b[2]}}' in
share|improve this answer

You are almost there, just need to adjust the sort options:

sort -k2,2 -k1,1r myfile.txt | uniq -f1

That is: sort by user and reverse date, leave only first appearance of user + access.

share|improve this answer
    
Thank you, it works! –  gakhov Jan 25 '12 at 13:10

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.