如何使用'mv'命令移动除特定目录中的文件以外的文件?

问题描述 投票:33回答:6

我想知道 - 我如何移动目录中的所有文件,除了特定目录中的那些文件(因为'mv'没有'--exclude'选项)?

linux mv
6个回答
67
投票

我们假设dir结构是这样的,

|parent
    |--child1
    |--child2
    |--grandChild1
    |--grandChild2
    |--grandChild3
    |--grandChild4
    |--grandChild5
    |--grandChild6

我们需要移动文件,看起来像,

|parent
    |--child1
    |   |--grandChild1
    |   |--grandChild2
    |   |--grandChild3
    |   |--grandChild4
    |   |--grandChild5
    |   |--grandChild6
    |--child2

在这种情况下,您需要排除两个目录child1child2,并将其余目录移动到child1目录中。

使用,

mv !(child1|child2) child1

这会将所有其余目录移动到child1目录中。


3
投票

由于find确实有一个exclude选项,因此请使用find + xargs + mv:

find /source/directory -name ignore-directory-name -prune -print0 | xargs -0 mv --target-directory=/target/directory

请注意,这几乎是从查找手册页复制的(我认为使用mv --target-directory比cpio更好)。


1
投票

这不是你要求的,但它可能会起作用:

mv the-folder-you-want-to-exclude somewhere-outside-of-the-main-tree
mv the-tree where-you-want-it
mv the-excluded-folder original-location

(基本上,将排除的文件夹移出要移动的较大树。)

所以,如果我有a/,我想排除a/b/c/*

mv a/b/c ../c
mv a final_destination
mkdir -p a/b
mv ../c a/b/c

或类似的东西。否则,你可能会得到find来帮助你。


1
投票

这会将当前目录中或者不在./exclude/目录中的所有文件移动到/ wherever ...

find -E . -not -type d -and -not -regex '\./exclude/.*' -exec echo mv {} /wherever \;

0
投票
#!/bin/bash

touch apple  banana  carrot  dog  cherry

mkdir fruit

F="apple  banana  carrot  dog cherry"

mv ${F/dog/} fruit

#这将从列表OF中删除'dog',因此它保留在当前目录中而不会移动到'fruit'


0
投票
ls | grep -v exclude-dir | xargs -t -I '{}' mv {} exclude-dir
© www.soinside.com 2019 - 2024. All rights reserved.