简体   繁体   English

如何从shell命令中删除目录中的每个其他文件?

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

I have extracted frames from a video in png format: 我从png格式的视频中提取了帧:

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? 我想使用shell命令从dir中删除每个其他帧,该怎么做?

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. 我需要动态地在一个命令中完成所有这些操作,因为文件夹中有数千个图像。

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". 这将消除名称以“1”或“3”或“5”或“7”或“9”加尾随“.png”结尾的每个文件。

Note: * used in pattern stands for 0 or more characters so 1.png will match but so would foo1.png 注意: *在模式中使用*表示0 or more characters因此1.png将匹配,但foo1.png也是如此

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: 您可以选择使用xargs加快速度:

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. 有很多方法可以达到理想的效果。

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. 对于dos / windows,将“rm”替换为“erase”。

假设每隔一个意味着文件的结尾数字为1,3,5,7或9,那么这就解决了你的问题

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

Other than what? 除了什么? You can use * to delete multiple frames. 您可以使用*删除多个帧。 For example rm -f *.png to delete all. 例如rm -f * .png删除全部。

This small script remove all png files: 这个小脚本删除所有png文件:

$ 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: 现在,删除所有没有 png扩展名的文件:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM