Awk & Move

How can I move all files from last year. I wrote the comamnd but not working.

 ls -ltr | awk '{if($8~/2009/)print "mv "$9 " remove"}'
ls -ltr | awk '$8~"2009"{system("mv "$9 " remove")}'

hmmm..not sure that worked

ls -ltr | awk '$8~"2007"{system("mv "$9 " remove")}'
awk: syntax error near line 1
awk: bailing out near line 1

I have the files there still

-rw-r--r-- 1 romi romi 391074 May 5 2007 17290.trc.failover
-rw-r--r-- 1 romi romi 9390653 May 5 2007 trc.failover
-rw-r--r-- 1 romi romi 378428 May 5 2007 10636.trc.failover

Are you using Solaris or other Unix (not Linux)?

SunOS 5.8 Generic_117350-53 sun4u sparc SUNW,Sun-Fire-V490

Try:

ls -ltr | /usr/xpg4/bin/awk '$8~"2007"{system("mv "$9 " remove")}'

aah yes that worked...thank you sir :slight_smile:

At a slight step-back perspective, it helps to name files or dirs with dates, since a file can be touched forward or backward in time, so you pick up too many or too few!

There are a few other ways to examine the date without the clutter of ls -ltr. Beware: many methods are sensitive to meta and white space characters in the file names. The find -exec is not sensitive, but lacks economy of scale, not much of an issue if the files stay on the same device (mv is just rename (ln and rm), not cp and rm). Note that if you do not want 'find' to recurse down the tree, it can be given file names not directories, but then remember that command line length is often large but not unlimited.

touch -t 200701010000 /tmp/2007a
touch -t 200801010000 /tmp/2008a
find ... -type f -newer /tmp/2007a ! -newer /tmp/2008a | xargs -n99 echo | while read l
do
 mv $l remove
done

Narrative: make files modified first second of 2007 and 2008, use them with find -newer to find files in the time range, block them up 99 to a line or less, and run mv on each block.

1 Like