将除1之外的所有目录移动到另一个文件夹(如果存在),将所有文件保留在后面

时间:2012-11-11 05:18:27

标签: regex bash if-statement case mv

我正在尝试将一些目标从一个位置移动到另一个位置,但我需要将一个位置留在原位(所有文件都将保留在原位)。我尝试过几件事,但似乎没什么用。 我测试了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

2 个答案:

答案 0 :(得分:3)

跳过条件和案例陈述。

find path/to/dir/*  \! -name 'this_dir_stays_put' -type d -maxdepth 0 \
   -exec mv {} new/location \;

答案 1 :(得分:0)

我假设你有这样的事情:

dir_a
dir_b
dir_c
dir_d
dir_e

您想要移动除dir_c以外的所有目录。

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

好的,如果你使用Kornshell,那很简单。如果您使用Bash,则需要先设置extglob选项,如下所示:

$ shopt -s extglob

现在,您可以使用extended globbing syntax指定目录例外:

$ mv !(dir_c) $new_location

!(dir_c)匹配除dir_c以外的所有文件。这适用于Kornshell。它适用于BASH,但仅限于您首先设置extglob

相关问题