Deleting files with a for loop |
Here's a real life example I encountered today.
In a particular directory there were a large number of files with
sequential filenames in the form 1002.tif, 1003.tif up to about
10200.tif.
We needed to delete all files with a date before 1st December (just
over a month ago).
Thinking about things now, we could have used the find command,
but I would have had to read the manual to check the exact syntax.
This is what we did:
Created a list of all the file names:
$ ls > tmp
used vi to delete the last portion of the file containing the filenames
we wanted to keep:
$ vi tmp
(use 'G' to jump to the end of the file, ^B to move back a page at a
time or ?pattern to search backwards through the file for pattern.
Once you've found the first file you want to keep, put the cursor on
that line and use 'dG' to delete from here to the end of the file.)
Now we used a for command to do the deleting:
$ for i in `cat tmp`
> do
> rm $i
> done
$
The single back quotes around 'cat tmp' gets the shell to execute
this as a command and substitute the resultant output where the
command was. So, effectively we'll end up with a list of files we
want to delete.
The variable i gets set to each filename in turn. The do...done loop
executes the rm command for each value of i.
Done :-)
If this tip was useful to you, or you thought you could improve it, or you have any other suggestions, please email me on unix_scripts at dr-jan.com so I can incorporate any useful stuff into the next version.
You'll have to translate that email address. Unfortunately I have to do things this way to avoid spam. :-(