脚本删除每个目录中最旧的文件类型?

时间:2014-02-03 19:32:11

标签: bash

许多研究已经变成了几乎相似的问题,但没有足够接近让我知道如何完成我的任务。我将尽力保持清晰和简短,同时解释情况和期望的结果。我的结构如下:

-mobile  
--Docs  
--Downloads  
--SomeFile  
----this.is.crazy_0.0.1-1_named-silly.txt 
----dont.touch.me.pdf
----leave.me.alone.png 
----this.is.crazy_0.0.1-2_named-silly.txt  
----this.is.crazy_0.0.1-3_named-silly.txt <---- file to keep  
--SomeFileA  
----this.is.crazy_0.0.1-1_also-silly.txt  
----this.is.crazy_0.0.1-2_also-silly.txt
----dont.touch.me.either.pdf
----leave.me.alone.too.png  
----this.is.crazy_0.0.1-3_also-silly.txt  
----this.is.crazy_0.0.1-11_also-silly.txt <----file to keep  

我的脚本中找到.txt文件的第一部分忽略了这个工作目录中的每个目录,并将它们打印到一个列表中(这是一个完全丑陋的黑客攻击,很可能是阻碍大多数人实现这个目标的方式任务)“SomeFileB和SomeFileC”可以带有相同的文件结构,我也想在这个脚本中捕获它们。

这个想法是根据时间戳保留每个目录中的最新.txt文件,这显然不在文件名中。要保留的文件当然会继续改变。为了再次澄清这个问题,如何根据文件名中没有的时间戳,将每个变量目录中的最新.txt文件保存为变量疯狂名称?希望我已经足够清楚地寻求帮助了。这个脚本应该是bash。

我现在没有使用当前的代码,因为我说它很难看,但是这是我所拥有的代码片段find /path/to/working/directory -maxdepth 0 -not -path "*Docs*" -not -path "*Downloads* -name "*.txt" >list

1 个答案:

答案 0 :(得分:1)

假设问题被正确理解,任务可以表示为:

递归删除除每个目录中最新文件之外的所有文件*.txt

#!/bin/bash

# Find all directories from top of tree
find a -type d | while read -r dir; do

    # skip $dir if doesn't contain any files *.txt
    ls "$dir"/*.txt &>/dev/null || continue

    # list *.txt by timestamp, skipping the newest file
    ls -t "$dir"/*.txt | awk 'NR>1' | while read -r file; do
        rm "$file"
    done
done

假设这个目录树,a.txt始终是最新的:

$ tree -t a
a
├── otherdir
├── b
│   ├── d e
│   │   ├── a.txt
│   │   ├── b.txt
│   │   ├── c.txt
│   │   ├── bar.txt
│   │   └── foo.pdf
│   ├── c
│   │   ├── a.txt
│   │   ├── b.txt
│   │   └── c.txt
│   ├── a.txt
│   ├── b.txt
│   ├── c.txt
│   └── foo.pdf
├── a.txt
├── b.txt
└── c.txt

这是运行脚本后的结果:

$ tree -t a
a
├── b
│   ├── c
│   │   └── a.txt
│   ├── d e
│   │   ├── a.txt
│   │   └── foo.pdf
│   ├── a.txt
│   └── foo.pdf
├── otherdir
└── a.txt

rm "$file"更改为echo rm "$file"以检查在运行“for real”之前将删除的内容

相关问题