Tuesday 13 December 2011

[BASH] Sorting by date and creating generic functions

[BASH] Sorting by date and creating generic functions

Hello again.

I'm currently using the following technique to sort a file called details.csv

Code:

sort -d -o details.csv -t , -k 3,3 details.csv
Within the csv file I only have 3 fields. A name, number and date of birth.

Example:
Code:

fred,999,03/04/2005
jane,888,01/01/1993
james,3456,12/01/1987
john,1234,11/08/1955

When I call the above sort, it is sorting the third field but it's doing so by the day (the format is dd/mm/yyyy). I'd love it to sort correctly by the entire date, or if it's too much hassle I'm happy to just sort by year.

I've tried playing around with the sort function, but this is the best way I can come up with without breaking everything. Hopefully one of you knowledgeable chaps can point me in the right direction.

Secondly, I have 2 functions that do the same job, but with different variables. Is there a way to just use one of these functions and return the "chopped" variable?

Code:

chop_name() {

       
        length=`echo ${#name}`
       
        if [ $length -gt 6 ]
        then
                name=`echo ${name:0:6}`
                name=$name".."
                cut="true"
        fi       
       
}

chop_number() {
       
        length=`echo ${#number}`
       
        if [ $length -gt 6 ]
        then
                number=`echo ${number:0:6}`
                number=$number".." #place dots at the end to show number's been chopped
                cut="true"
        fi       
}

Thanks again :)

No comments:

Post a Comment