L
L
linqu2020-09-16 11:48:25
Perl
linqu, 2020-09-16 11:48:25

Perl - how to find symbolic links?

It is necessary to find in the directory all symbolic links that refer to files or directories in the specified path.
I am a complete layman in Perl, how to do it in this language - I have no idea. In bash, everything is elementary:

find_dir=/home/someuser/Desktop
to_dir=/tmp/someuser/tmpmounts
ls -la ${find_dir} | awk '\$11 ~ \"${to_dir}\" {print ${find_dir}/\$9}' | xargs rm

But the changes need to be made to the Perl project, so the perl code is needed

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry, 2020-09-16
@linqu

Similar code example in perl

#!/usr/bin/perl

$find_dir = '.';
$to_dir = '/tmp/test';

foreach(glob("$find_dir/*"))
{
        print "checking $_ \n";
        $link_path = readlink($_);
        if($link_path ne '')
        {
                print "..found symlink $link_path \n";
                if($link_path =~ /^$to_dir/)
                {
                        print "....found matched symlink!\n";
                        # do something ...
                        # for example delete found file
                        # unlink($link_path)
                }
        }
}

On the test folder with contents
drwxrwxr-x 2 dt dt 4096 сен 16 12:08  1
lrwxrwxrwx 1 dt dt    4 сен 16 12:18  2 -> /tmp
lrwxrwxrwx 1 dt dt    9 сен 16 12:18  3 -> /tmp/test
lrwxrwxrwx 1 dt dt   18 сен 16 12:19  4 -> /tmp/test/test.txt
lrwxrwxrwx 1 dt dt   29 сен 16 12:19  5 -> '/tmp/test/tes test test 2.txt'
lrwxrwxrwx 1 dt dt   29 сен 16 12:19 'tes test test 2.txt' -> '/tmp/test/tes test test 2.txt'
-rwxr-xr-x 1 dt dt  387 сен 16 12:22  test.pl
Gives the following:
checking ./1 
checking ./2 
..found symlink /tmp 
checking ./3 
..found symlink /tmp/test 
....found matched symlink!
checking ./4 
..found symlink /tmp/test/test.txt 
....found matched symlink!
checking ./5 
..found symlink /tmp/test/tes test test 2.txt 
....found matched symlink!
checking ./tes test test 2.txt 
..found symlink /tmp/test/tes test test 2.txt 
....found matched symlink!
checking ./test.pl

P
pcdesign, 2020-09-16
@pcdesign

Here is a one-liner to find symlinks in the /tmp folder

perl -E 'for $f (glob "/tmp/*") {say $f if (-l $f)}'

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question