'Unix Command to delete siblings and parent directory of a given file

I have a directory structure like this

/home
   /dir-1
      some-file.php
   /dir-2
      sibling.php
      target-file.php
   /dir-3
   /dir-4
      other-sibling.php
      sibling.php
      target-file.php
   /dir-5
      target-file.php

I need to target all directories containing the file "target-file.php" and remove those directories with its contents. In my structure, the final result wanted is:

/home
   /dir-1
      some-file.php
   /dir-3

I am trying:

rm -rf /home/*/target-file.php

But it is only removing that file (target-file.php) and not the siblings or the parent directory.

Please help



Solution 1:[1]

Use this:

#!/bin/bash

find . -type f -name target-file.php -print0 | while IFS= read -r -d '' line
do
    echo "$line"
    /bin/rm -fr "$(dirname "$line")"
done
  • Using find with while like this ensure it will work with all filenames (see https://mywiki.wooledge.org/BashFAQ/001).
  • You can run find . -type f -name target-file.php -print to see the list of files.
  • dirname removes the filename so you are left with only the directory names.
  • /bin/rm -fr deletes the directories.
  • you can comment the echo line, this was just to show you the files / directories being processed.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nic3500