在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/
相關文章
相關標籤/搜索