user967451
user967451

Reputation:

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.

Upvotes: 20

Views: 14978

Answers (6)

Marcin Orlowski
Marcin Orlowski

Reputation: 75629

This should do the trick:

rm -f *[13579].png

which would exterminate every file which name ends with 1 or 3 or 5 or 7 or 9 plus trailing .png suffix.

Note: * used in pattern matches 0 or more characters so foo1.png would be removed, but so would 1.png.

Upvotes: 44

b3h3m0th
b3h3m0th

Reputation: 1376

This small script remove all png files:

$ find . -name "*.png" -exec /bin/rm {} \;

Pay attention to the dot, it means current directory.

It's the same, but more secure:

$ find . -name "*.txt" -delete:

Now, remove all files that does not have png extension:

$ find  . ! -name "*.png" -type f -delete

Upvotes: -1

Jonathan Leffler
Jonathan Leffler

Reputation: 753695

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.

Upvotes: 30

Benny Smith
Benny Smith

Reputation: 249

rm ???????1.png
rm ???????3.png
rm ???????5.png
rm ???????7.png
rm ???????9.png

(but make a backup before you try it!). Replace "rm" with "erase" for dos/windows.

Upvotes: 5

Dmitry Stukalov
Dmitry Stukalov

Reputation: 192

Other than what? You can use * to delete multiple frames. For example rm -f *.png to delete all.

Upvotes: -1

Nejc
Nejc

Reputation: 700

Suppose every other means files with ending digit 1, 3, 5, 7 or 9, then this solves your problem

find . -regex '.*[13579]\.png' -exec rm {} \;

Upvotes: 1

Related Questions