Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I want to use the following command to delete directories dated Jan 2010 only

ls -lh | awk '{print $6 " " $9}' | sed -n '/Jan/p' | awk '{print $2}' >>/tmp/file_list

The above command will list all directories dated Jan, but I have in my list Jan 2010 and Jan 2011.

Can anyone can help me with the SED command to list only the directories date Jan, 2010?

share|improve this question
find is specifically created to solve problems like that. Take the time to master it, it make problems like this seam trivial. – nelaar Aug 4 '11 at 7:54
up vote 1 down vote accepted

You can use grep instead of awk/sed, maybe something like this?

ls -lh | grep -o 'Jan [ 1-2][0-9]  2010 .*$' | awk '{print $4}' >> /tmp/file_list

The problem with what you have is the first awk is not including the years, so 2011 (or 2009, 2008, etc) all show up in the list that gets sent to sed.

share|improve this answer
thank you for your answer, i got the list of directories but is there a way to print date in the output file? – AlBouazizi Aug 2 '11 at 7:10
If you want the date and the file, you can get rid of the last awk (which prints the file only). Without the last awk, you will get: "Jan" then the date, then "2010" then the filename. – Jon Lin Aug 2 '11 at 7:15

Never attempt to parse the output of ls for anything other than display purposes --- it is a bad idea.

Though it uses find and xargs instead of sed, maybe something like this would work. Note that it is untested.

jan01="$(date -d '20100101 00:00' +%s)"
feb01="$(date -d '20100201 00:00' +%s)"

today="$(date -d '23:59:59' +%s)"

daysecs="$((24*60*60))" # 86400 

dayssincefeb01="$(((today - feb01) / daysecs ))"
dayssincejan01="$(((today - jan01 + 1) / daysecs ))"

find /path -type d -mtime +"$dayssincefeb01" -mtime -"$dayssincejan01" \
-print0 | xargs -0 rm -r

The find command at the end finds directories that are older than 01 Feb 2010 but younger than 01 Jan 2010 and pipes them safely to xargs using the '\0' null character.

share|improve this answer
./ line 1: 24*60*60: command not found ./ line 8: ): syntax error: operand expected (error token is ")") ./ line 9: ): syntax error: operand expected (error token is ")") find: invalid argument +' to -mtime' – AlBouazizi Aug 2 '11 at 8:30
@AlBouazizi Sorry I had a typo on that line (missing a parenthesis). Should be fixed now. – jw013 Aug 2 '11 at 8:42
thank you for your effort.. i want to test the output with xargs -0 ls -l >>output.file is it doable? – AlBouazizi Aug 2 '11 at 9:11
You can just replace the rm -r with ls -l. – jw013 Aug 2 '11 at 9:23

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .