Shell – Get files with a name containing a date value less than or equal to a given input date

greplinuxshell

One of my folders contains files in the following format:

3_20150412104422154033.txt
3_2015041211022775012.txt
3_20150412160410171639.txt
3_20150412160815638933.txt
3_20150413161046573097.txt
3_20150413161818852312.txt
3_20150413163054600311.txt
3_20150413163514489159.txt
3_2015041321292659391.txt
3_20150414124528747462.txt
3_20150414125110440425.txt
3_20150414134437706174.txt
3_20150415085045179056.txt
3_20150415100637970281.txt
3_20150415101749513872.txt

I want to retrieve those files having a date value less than or equal to my input date value.

For example, if I give "3_20150414" which is (3_YYYYMMDD), I want the output to be the file names

3_20150412104422154033.txt
3_2015041211022775012.txt
3_20150412160410171639.txt
3_20150412160815638933.txt
3_20150413161046573097.txt
3_20150413161818852312.txt
3_20150413163054600311.txt
3_20150413163514489159.txt
3_2015041321292659391.txt
3_20150414124528747462.txt
3_20150414125110440425.txt
3_20150414134437706174.txt

I can list the files by issuing a command like this:

ls -l | grep '20150413\|20150414' |awk '{print $NF}'

But I am struggling to find a <= match.

Best Answer

You can use awk and its string comparison operator.

ls | awk '$0 < "3_20150415"'

In a variable:

max=3_20150414 export max
ls | LC_ALL=C awk '$0 <= ENVIRON["max"] "z"'

concatenating with "z" here makes sure that the comparison is a string comparison, and allows any time on that day since in the C locale, digits sort before z.

Related Question