![](/img/trans.png)
[英]How to empty(delete all contents) all files in a directory without deleting the files?
[英]Delete All Files In a Directory Without Deleting Symbolic Links and the Files They Point To
在一個特定目錄中,我希望能夠在刪除其余部分的同時保存符號鏈接及其指向的文件。
示例:/ home / me / test_dir ls
mylink file1.txt file2.txt file3.txt
隨着時間的流逝,“ mylink”指向了file1.txt,然后是file2.txt,現在是file3.txt
mylink-> /home/me/test_dir/file3.txt
我可以執行以下哪行命令來刪除file1.txt和file2.txt? 我有大約80萬個文件需要刪除。
謝謝。
這是一個腳本,如果該目錄中沒有指向它們的符號鏈接,則該腳本將從目錄中刪除這些文件。
#!/usr/bin/perl
# Usage: perl rmlinks.pl DIRECTORY
use warnings;
use strict;
use autodie;
use Cwd qw/abs_path/;
my $dirname = shift;
opendir(my $dir, $dirname);
chdir $dirname;
my %referenced;
while (my $file = readdir $dir) {
$referenced{abs_path(readlink $file)} = 1 if -l $file;
}
rewinddir $dir;
while (my $file = readdir $dir) {
unlink $file if -f $file && ! -l $file && !exists $referenced{abs_path $file};
}
closedir $dir;
它嘗試同時考慮絕對符號鏈接路徑和相對符號鏈接路徑,但使用后果自負。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.