2013-05-01 43 views
0

我熟悉的如何使用字符串作爲參數在爲... ...在Linux中殼聲明

for file in foo/folder\ with\ spaces/foo2/*.txt 
do 
    #do some stuff... 
done 

但是結構,我想提出foo/folder with spaces/foo2/*.txt到一個變量然後使用它。事情是這樣的:

myDirectory="foo/folder with spaces/foo2/*.txt" 

for file in $myDirectory 
do 
    # do some stuff 
done 

但是我在這裏寫是不行的,即使我做

myDirectory="food/folder\ with\ spaces/foo2/*.txt" 

for file in "$myDirectory" ... 

任何幫助將無法正常工作?這甚至有可能嗎?

回答

-1

嘗試在for循環中使用ls命令。這個工作對我來說:

for file in `ls "$myDirectory"` 
+0

謝謝!那正是我需要的! – WhiteTiger 2013-05-01 19:05:55

+1

不要這樣做。對於名稱中包含空格的文件將會失敗。 – chepner 2013-05-01 21:04:32

+0

這當然不是你所需要的,這會導致麻煩,你真的應該看看@ glennjackman的回答。 – 2013-05-02 08:39:03

6

don't parse ls

# your files are expanded here 
# note lack of backslashes and location of quotes 
myfiles=("food/folder with spaces/foo2/"*.txt) 

# iterate over the array with this 
for file in "${myfiles[@]}"; do ... 
1

解析LS是一個壞主意,而不是僅僅做外殼通配符引號之外。

你也可以這樣做:

$mydir="folder/with spaces" 

for file in "$mydir"/*; do 
    ... 
done 

還應考慮如何findxargs作品。使用這些問題可以解決許多這類問題。如果您想要安全,請特別注意-print0-0選項。

相關問題