【问题标题】:how to delete a sub directory whose name is appended to the end of its parent folder's name如何删除名称附加到其父文件夹名称末尾的子目录
【发布时间】:2021-01-29 23:58:21
【问题描述】:

父文件夹包含在末尾附加的子目录名称

分隔符是下划线_:

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)

不确定如何删除子目录。 请帮忙!

【问题讨论】:

  • rmdir */_* 有什么问题?
  • @user1934428:它也会删除具有不同后缀的目录。
  • 我知道它应该删除所有目录下一层,以取消划线开头。然后你必须描述要删除的目录应该是什么样子,哪些应该不理会?

标签: bash find cut xargs


【解决方案1】:

遍历目录,使用参数扩展删除最后一个下划线之前的所有内容:

#! /bin/bash
for dir in * ; do
    last=${dir##*_}
    [[ -d $dir/$last ]] && rmdir "$dir/$last"
done

【讨论】:

  • 嗨@choroba 这个脚本放在哪里?我不知道如何给目录输入
  • 把它放在任何你喜欢的地方,从层次结构的根目录调用它。或者,将根目录作为参数发送,并以cd "$1" || exit 1 启动脚本。
  • 我放置在需要处理的目录旁边或同一级别。它没有工作
  • 只需删除last=之后的_
  • 如果目录不为空,请使用rm -rf 而不是rmdir
【解决方案2】:
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#**} 去除最后一个字符,然后删除目录路径(如果存在)。

在删除要执行的注释标记之前回显删除命令。

【讨论】:

  • 利用find命令-print0option到handle file names containing newlines并在你的while循环中处理它们,将while read dir更改为while IFS= read -r -d '' dir
  • 感谢@RobC 的输入,我已经通过改进修改了答案。
  • @RamanSailopal 如何将输入的根目录名称传递给此脚本?
  • 替换 .在寻找路径
  • 您好,我将上面的代码复制到 test2.sh 中并放在 a_b_c 旁边并使用 bash test2.sh 执行。它没有回应命令。我做错了吗?
猜你喜欢
  • 2022-10-07
  • 1970-01-01
  • 2011-05-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多