Search code examples
unixlsuniq

UNIX - count unique values based on file modification date


I want to count the number of different years of all files in a specific directory, based upon the file modification date. My directory is /filehistory

For example, there are many thousands of files in my directory. I want to count the number of different years as it pertains to modification date. If all files were from the year 2014, then my answer is 1. If all files are from 2013 and 2014 then my answer is 2. And so on...

ls -l /filehistory | ????

I am unsure what to do after the pipe in the above command. Can somebody please advise me?


Solution

  • There may be better alternatives, but try this one:

    ls -lT | tr -s ' ' | cut -d ' ' -f 9 | sort | uniq | wc -l
    

    ls -lT : Displays detailed listing with modified date and year in full.

    tr -s ' ' : Removes excess space

    cut -d ' ' -f 9: Collect the year column

    sort: Sort the years

    uniq: Collect the unique years

    wc -l: Count the number of lines.