linuxshellfilesymlink

Remove all symlinks that are pointing to specific directory


I created a lot of symbolic links in /usr/lib that point to different folder files /var/lib/temp,/tmp/xyz..etc

How to delete all the symbolic links (temp1.txt, temp2.txt, temp3.txt) pointing to /var/lib/temp, but keep the remaining links (temp4.txt, temp5.txt)?

Example:

/usr/lib/temp1.txt -> /var/lib/temp/temp1.txt
/usr/lib/temp2.txt -> /var/lib/temp/temp2.txt
/usr/lib/temp3.txt -> /var/lib/temp/temp3.txt

/usr/lib/temp4.txt -> /tmp/xyz/temp4.txt
/usr/lib/temp5.txt -> /tmp/xyz/temp5.txt

We can traverse each symlink in /usr/lib, get realpath, then check if real path contains /var/lib/temp then remove it. However trying to find an optimal solution.


Solution

  • With GNU findutils version of find, it is just:

    find /usr/lib -lname '/var/lib/temp/temp[123].txt' -delete