TK123 TK123 - 5 months ago 14
Linux Question

How to delete every other file in a directory from a shell command?

I have extracted frames from a video in png format:

00000032.png
00000033.png
00000034.png
00000035.png
00000036.png
00000037.png


and so on...

I would like to delete every other frame from the dir using a shell command, how to do this?

EDIT



I think I wasn't clear in my question. I know I can delete each file manually like:

rm filename.png
rm filename2.png


etc...

I need to do all this in one command dynamically because there are thousands of images in the folder.

Answer
delete=yes
for file in *.png
do
    if [ $delete = yes ]
    then rm -f $file; delete=no
    else delete=yes
    fi
done

This forces strict alternation even if the numbers on the files are not consecutive. You might choose to speed things up with xargs by using:

delete=yes
for file in *.png
do
    if [ $delete = yes ]
    then echo $file; delete=no
    else delete=yes
    fi
done |
xargs rm -f

Your names look like they're sane (no spaces or other weird characters to deal with), so you don't have to worry about some of the minutiae that a truly general purpose tool would have to deal with. You might even use:

ls *.png |
awk 'NR % 2 == 1 { print }' |
xargs rm -f

There are lots of ways to achieve your desired result.

Comments