在UNIX / Linux Shell中进行模式匹配时,如何使用反或负通配符?

假设我要复制目录的内容,但文件和文件夹的名称中不包含“ Music”一词。 bash

cp [exclude-matches] *Music* /target_directory

要实现此目标,应该用什么代替[排除匹配]? spa


#1楼

能够经过find找到一种解决方案。 code

$ mkdir foo bar
$ touch foo/a.txt foo/Music.txt
$ find foo -type f ! -name '*Music*' -exec cp {} bar \;
$ ls bar
a.txt

Find有不少选项,您能够很是明确地包含和排除哪些内容。 递归

编辑:亚当在评论中指出,这是递归的。 查找选项mindepth和maxdepth在控制此方面可能颇有用。 内存


#2楼

不以bash(我知道)为准,可是: get

cp `ls | grep -v Music` /target_directory

我知道这并非您要找的东西,可是它将解决您的示例。 event


#3楼

您还能够使用一个很是简单的for循环: 循环

for f in `find . -not -name "*Music*"`
do
    cp $f /target/dir
done

#4楼

在Bash中,您能够经过启用extglob选项来作到这一点(例如,用cp替换ls并添加目标目录) grep

~/foobar> shopt extglob
extglob        off
~/foobar> ls
abar  afoo  bbar  bfoo
~/foobar> ls !(b*)
-bash: !: event not found
~/foobar> shopt -s extglob  # Enables extglob
~/foobar> ls !(b*)
abar  afoo
~/foobar> ls !(a*)
bbar  bfoo
~/foobar> ls !(*foo)
abar  bbar

您能够稍后使用禁用extglob 方法

shopt -u extglob

#5楼

若是您想避免使用exec命令的内存成本,我相信使用xargs能够作得更好。 我认为如下是更有效的替代方法

find foo -type f ! -name '*Music*' -exec cp {} bar \; # new proc for each exec



find . -maxdepth 1 -name '*Music*' -prune -o -print0 | xargs -0 -i cp {} dest/
相关文章
相关标签/搜索