问题描述
父文件夹包含末尾附加的子目录名称
分隔符为下划线 _
:
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)
|..
输出应该是
a_b_c (parent folder contains sub directory name at the end)
|..
d_f
|..
g_h
|..
我所拥有的是获取子目录名称
"$PWD" |rev|cut -d"_" -f1|rev (input: a_b_c output: c)
不知道如何删除子目录。 请帮忙!
解决方法
遍历目录,使用参数扩展删除最后一个下划线之前的所有内容:
#! /bin/bash
for dir in * ; do
last=${dir##*_}
[[ -d $dir/$last ]] && rmdir "$dir/$last"
done
,
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)"
利用 find 执行正则表达式搜索仅具有模式概述的目录,将输出重定向回 while 循环,将它们读入变量 dir。然后我们用 ${dir#**} 去掉最后一个字符,然后删除目录路径(如果存在)。
在删除要执行的注释标记之前回显删除命令。