在bash中列出具有目录路径空格的文件问题

6
在命令行中进入目录时,输入以下命令:
ls -d -1 "/Volumes/Development/My Project/Project"/**/* | grep \.png$

打印出所有以.png结尾的文件列表。
但是,当我尝试创建一个脚本时:
#! /bin/bash

clear ;

# Tempoary dir for processing
mkdir /tmp/ScriptOutput/ ;

wdir="/Volumes/Development/My Project/Project" ;

echo "Working Dir: $wdir" ;

# Get every .PNG file in the project
for image in `ls -d -1 "$wdir"/**/* | grep \.png$`; do
...    
done

I get the error:

cp: /Volumes/Development/My: No such file or directory

空格 造成了问题,但我不知道为什么?

4个回答

6

另一个选择是更改IFS:

OLDIFS="$IFS"  # save it
IFS="" # don't split on any white space
for file in `ls -R . | grep png`
do 
    echo "$file"
done
IFS=$OLDIFS # restore IFS

请在 man bash 中了解有关IFS的更多信息。


2

1

如果您习惯于使用while read和通过管道创建的子进程,您可以这样做:

find . -name '*.png' | while read FILE
do 
    echo "the File is [$FILE]"
done

您甚至可以使用 'find . -name '*.png' -exec echo {} \;'。如果需要,可以多次使用 find 的 -exec 选项。 - jfg956
对于一个命令(比如这里的echo),最好使用-exec(如果有多个文件,则使用|xargs可以提高性能)。对于多个命令,我更喜欢使用while循环。这样更容易阅读。干杯。 - Michał Šrajer

0
可以尝试在空格处使用 [[:space:]]。
wdir="/Volumes/Development/My[[:space:]]Project/Project"

或执行命令以将单个空格转换

wdir=`echo "$wdir" | sed 's/[[:space:]]/\[[:space:]]/g'`

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接