Bash:有条件地移动嵌套重复目录


0

假设我有一个名为“ foo”的目录,其中包含几个目录:

foo/bar/bar/(files)
foo/bat/bat/(files)
foo/baz/qux/(files)

有没有办法有条件地将“最深”目录上移,以便仅在其名称与父目录名称匹配时才替换其父目录?如果不匹配,则目标是保留当前目录结构。

所需的输出:

foo/bar/(files)
foo/bat/(files)
foo/baz/qux/(files)

Answers:


0

您可以使用find

find . -regextype posix-awk -type d -regex ".*/(.*)/\1$" -exec sh -c "mv {}/* {}/../" \; -delete
  • -regextype posix-awk:我们需要使用posix-awkregextype才能使用向后引用(\1
  • -type d:目标目录
  • -regex ".*/(.*)/\1$":目标文件对应于 */bar/bar
  • -exec sh -c "mv {}/* {}/../":将目标目录移动到其父目录
  • -delete:删除目标目录

注意:您不能rmdir {}在内使用-execfind会返回No such file or directory错误),您需要在之后使用-delete选项-exec


0

未经测试:

DIR=foo
ls $DIR | while read SUBDIR ; do
  [ -d $DIR/$SUBDIR/$SUBDIR ] || continue
  mv $DIR/$SUBDIR/$SUBDIR/* $DIR/$SUBDIR/
  rmdir $DIR/$SUBDIR/$SUBDIR
done
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.