【问题标题】:Delete All Files In a Directory Without Deleting Symbolic Links and the Files They Point To删除目录中的所有文件而不删除符号链接及其指向的文件
【发布时间】:2018-12-27 03:48:19
【问题描述】:

在特定目录中,我希望能够保存符号链接和它们指向的文件,同时删除其余部分。

示例:/home/me/test_dir ls

我的链接 文件1.txt 文件2.txt 文件3.txt

随着时间的推移,“mylink”指向 file1.txt,然后是 file2.txt,现在是 file3.txt

mylink -> /home/me/test_dir/file3.txt

我可以执行什么行命令来只删除 file1.txt 和 file2.txt?我有大约 80 万个文件需要删除。

谢谢。

【问题讨论】:

  • 您只想删除没有指向它们的符号链接的真实文件?您是否担心来自其他地方的符号链接,而不仅仅是这个特定目录?
  • @Shawn 问题 1:是,问题 2:否。
  • 请避免"Give me the codez" 问题。而是显示您正在处理的脚本并说明问题所在。另见How much research effort is expected of Stack Overflow users?

标签: linux hyperlink find rm


【解决方案1】:

这是一个脚本,如果该目录中没有指向它们的符号链接,则该脚本会从该目录中删除常规文件。

#!/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;

它尝试考虑绝对和相对符号链接路径,但使用风险自负。

【讨论】:

    猜你喜欢
    • 2015-01-20
    • 1970-01-01
    • 2011-08-19
    • 2013-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-05
    • 1970-01-01
    相关资源
    最近更新 更多