Click to See Complete Forum and Search --> : simple bash script


saeed_contractor
12-09-2001, 07:13 PM
I'm trying to write a script that will delete all files in a directory that don't have a .txt extension, but I seem to be having trouble with the logic. How do I get it to differentiate between .txt files and non .txt files. (it's deleting everything now)
Thanks :confused:

bwkaz
12-09-2001, 07:47 PM
Do a shopt extglob. If it comes back with "extglob on", you can put this in your script:

rm -f /path/to/files/!(*.txt)

If it's off, then something like this may work, however, its running time is pretty crappy and I think you should rather just turn on extglob with shopt -s extglob. But that's just me, here's the code:

for file in $(ls) ; do
istxt = "no"

for txtfile in $(ls *.txt) ; do
if [ file = txtfile ] ; then
istxt = "yes"
fi
done

if [ $istxt = "no" ] ; then
rm -f $file
fi
done

As you can see, it takes every file in the directory, and compares it to the set of files that are .txt files. If it matches any one of them, it sets $istxt to "yes". After it's done all the comparisons, if $istxt is still "no", then it deletes the file.

The running time is CRAPPY, especially if you have a whole lot of files, or most of them are, in fact, .txt files, but it shouldn't be too horrible on a small directory.

[ 09 December 2001: Message edited by: bwkaz ]

saeed_contractor
12-09-2001, 08:02 PM
ahh so easy, I think I was making it harder than it needed to be.
thanks

The Kooman
12-09-2001, 11:46 PM
Originally posted by saeed_contractor:
<STRONG>I'm trying to write a script that will delete all files in a directory that don't have a .txt extension, but I seem to be having trouble with the logic. How do I get it to differentiate between .txt files and non .txt files. (it's deleting everything now)
Thanks :confused:</STRONG>


find . \! -name '*.txt' -exec rm -f \{} \;


if you don't want to recursively delete the files, then use

find . \! -name '*.txt' -prune -exec rm -f \{} \;


HTH