0

我正在尝试将一些目录从一个位置移动到另一个位置,但我需要保留一个(所有文件都将保留在原位)。我已经尝试了几件事,但似乎没有任何效果。我已经测试了 DIR_COUNT 的值,它按预期工作。但是,当在条件语句或 case 语句中使用时,它不会按预期工作。

有条件的

#!/bin/bash
DIR_COUNT=$(find path/to/dir/*[^this_dir_stays_put] -type d -maxdepth 0 | wc -l)
echo $DIR_COUNT
if [[ $DIR_COUNT > 0 ]]
  then
    find path/to/dir/*[^this_dir_stays_put] -type d -maxdepth 0 -exec mv {} new/location \;
    echo "Moving dirs."
  else
    echo "No dirs to move."
fi

案子

#!/bin/bash
DIR_COUNT=$(find path/to/dir/*[^this_dir_stays_put] -type d -maxdepth 0 | wc -l)
echo $DIR_COUNT
case $DIR_COUNT in
  0)
    echo "No dirs to move."
  *)
    echo "Moving dirs."
    find path/to/dir/*[^this_dir_stays_put] -type d -maxdepth 0 -exec mv {} new/location \;;;
esac

使用这两个版本的代码,只要存在要移动的目录,一切都很好,但是如果没有要移动的目录,我就有问题了。

有条件的

$ sh script.sh
find: find path/to/dir/*[^this_dir_stays_put]: No such file or directory
0
No dirs to move.

案子

$ sh script.sh
find: find path/to/dir/*[^this_dir_stays_put]: No such file or directory
0
Moving dirs.
find: find path/to/dir/*[^this_dir_stays_put]: No such file or directory
4

2 回答 2

3

跳过条件和 case 语句。

find path/to/dir/*  \! -name 'this_dir_stays_put' -type d -maxdepth 0 \
   -exec mv {} new/location \;
于 2012-11-11T05:35:34.460 回答
0

我假设你有这样的事情:

dir_a
dir_b
dir_c
dir_d
dir_e

您想要移动除dir_c.

有时最简单的方法是将所有目录移动到新位置,然后将您想要的目录移回。不?

好的,如果你使用Kornshell它非常简单。如果使用Bash,则需要先设置如下extglob选项:

$ shopt -s extglob

现在,您可以使用扩展的通配语法来指定目录异常:

$ mv !(dir_c) $new_location

匹配!(dir_c)除. dir_c这适用于 Kornshell。它适用于 BASH,但前提是您首先设置了extglob.

于 2012-11-11T05:37:09.073 回答