0

我熟悉的结构

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" ...

有什么帮助吗?这甚至可能吗?

4

3 回答 3

6

不解析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 ...
于 2013-05-01T19:14:26.663 回答
1

解析 ls 是一个坏主意,而只是在引号之外执行 shell globbing。

你也可以这样做:

$mydir="folder/with spaces"

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

还要研究如何findxargs工作。许多此类问题都可以使用它们来解决。如果您想安全起见,请特别查看-print0and选项。-0

于 2013-05-01T19:54:35.573 回答
-1

尝试ls在 for 循环中使用该命令。这对我有用:

for file in `ls "$myDirectory"`
于 2013-05-01T18:55:21.047 回答