user2471320
user2471320

Reputation: 93

How to cut 5th field in unix with pipe delimitor and how to find minimum date value from that field

I have file, in that file 5th filed is date field . I want cut that field and find minimum value in that field.

Pl help me.

my date format is as follows:

05142013
05132013
05152013

Upvotes: 0

Views: 2125

Answers (2)

jaypal singh
jaypal singh

Reputation: 77135

This would work if you wish to do entirely with GNU awk.

awk  ' 
match($5,/(..)(..)(....)/,ldate) {
    ndate = mktime (ldate[3]" "ldate[1]" "ldate[2]" "0" "0" "0);
    fdate = (NR>1 && fdate < ndate) ? fdate : ndate
}
END {
print strftime("%d%m%Y",fdate)
}' FS="|" inputFile

Upvotes: 1

fedorqui
fedorqui

Reputation: 290025

cut is always good for cutting (obvious). So, cut -f5 can make it.

Regarding the minimum date, you can use sort. As you have the format like MMDDYYYY, to sort it based on the date you can do:

sort -k1.5,8                    -k1.1,2                 -k1.3,4            file
      year (5th to 8th chars)    month (first 2 chars)   day (3rd and 4th chars)

So all together should be

sort -k1.5,8 -k1,2 -k1.3,4 <(cut -f5 file)

Test

$ cat file
hello my name is 05142013
bye my name is 05132013
hello blabla name is 07132013
hello my name bloooo 02192013
hello you name is 05152013
hello my blabla is 05152012
$ sort -k1.5,8 -k1,2 -k1.3,4 <(cut -d" " -f5 file)
05152012
02192013
05132013
05142013
05152013
07132013

Update

As commented by devnull, it suffices with k1.5,8, as MMDD is the rest of the text to be sorted and there is no need to specify an un-default order.

sort -k1.5,8 <(cut -f5 file)

Upvotes: 2

Related Questions