-1

Parent folder contains subdir name appended at the end

Delimiter is underscore _:

a_b_c  (parent folder contains sub directory name at the end)
  |c/ (to be deleted)
  |..
d_f
  |..
  |f/ (to be deleted)
g_h
  |h/ (to be deleted)
  |..

Output should be

a_b_c  (parent folder contains sub directory name at the end)
  |..
d_f
  |..
g_h
  |..

What I have with me is get the subdirectory name

"$PWD" |rev|cut -d"_" -f1|rev  (input: a_b_c output: c)

Not sure how to delete the subdirectory. Help please!

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Dinesh Ravi
  • 1,209
  • 1
  • 17
  • 35

2 Answers2

3

Loop over the directories, use parameter expansion to remove everything before the last underscore:

#! /bin/bash
for dir in * ; do
    last=${dir##*_}
    [[ -d $dir/$last ]] && rmdir "$dir/$last"
done
choroba
  • 231,213
  • 25
  • 204
  • 289
1
while IFS= read -r -d '' dir;
do 
  if test -d "$dir/${dir#*_*_}";
  then 
       echo "rm -Rf $dir/${dir#*_*_}";
       # rm -Rf "$dir/${dir#*_*_}";
  fi;
done <<< "$(find . -type d -regextype posix-extended -regex "^.*[[:alpha:]]{1}_[[:alpha:]]{1}_[[:alpha:]]{1}$" -print0)"

Utilising find to execute a regular expression search for directories only that have the pattern outlined, redirect the output back into a while loop, reading them into a variable dir. We then strip the last character with ${dir#**} before removing the directory path if it exists.

Echo the remove command before removing the comment marker to execute.

Raman Sailopal
  • 12,320
  • 2
  • 11
  • 18