2011-12-14 178 views
14

我剛開始使用bash腳本,我需要使用find命令以及多種文件類型。在bash腳本中使用find命令

list=$(find /home/user/Desktop -name '*.pdf') 

爲PDF類型此代碼的工作,但我想搜索多個文件類型像.txt或.BMP together.Have你什麼想法?

回答

19

歡迎來到bash。這是一個古老的,黑暗而神祕的事物,具有很強的魔力。 :-)

你問的選項是find命令,但不是bash。在你的命令行中,你可以用man find來查看選項。

你要找的人是-o爲「或」:

list="$(find /home/user/Desktop -name '*.bmp' -o -name '*.txt')" 

也就是說...... 不要這樣做。像這樣的存儲可能適用於簡單的文件名,但只要您需要處理特殊字符(如空格和換行符),所有投注都將關閉。詳情請參閱ParsingLs

$ touch 'one.txt' 'two three.txt' 'foo.bmp' 
$ list="$(find . -name \*.txt -o -name \*.bmp -type f)" 
$ for file in $list; do if [ ! -f "$file" ]; then echo "MISSING: $file"; fi; done 
MISSING: ./two 
MISSING: three.txt 

路徑名擴展(globbing)提供了一個更好/更安全的方式來跟蹤文件。那麼你也可以使用bash數組:

$ a=(*.txt *.bmp) 
$ declare -p a 
declare -a a=([0]="one.txt" [1]="two three.txt" [2]="foo.bmp") 
$ for file in "${a[@]}"; do ls -l "$file"; done 
-rw-r--r-- 1 ghoti staff 0 24 May 16:27 one.txt 
-rw-r--r-- 1 ghoti staff 0 24 May 16:27 two three.txt 
-rw-r--r-- 1 ghoti staff 0 24 May 16:27 foo.bmp 

Bash FAQ有很多關於bash編程等優秀的提示。

3

您可以使用此:

list=$(find /home/user/Desktop -name '*.pdf' -o -name '*.txt' -o -name '*.bmp') 

此外,你可能想使用的-iname代替-name趕上文件與「.PDF」(大寫)擴展爲好。

+2

爲了應付與空格的文件名,您需要使用引號的` $ list`後面的變量,就像在`for $ in「$ list」;做echo $ i; done`。如果沒有雙引號,腳本會將每個「像this.jpg這樣的文件名」視爲三個文件:「filename」,「like」和「this.jpg」。 – ash108 2011-12-16 06:58:02