【问题标题】:Problem Listing files in bash with spaces in directory path问题在目录路径中列出带有空格的bash文件
【发布时间】:2011-10-17 08:27:57
【问题描述】:

在命令行中输入目录时,如下:

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

我得到错误:

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

空格导致问题,但我不知道为什么?

【问题讨论】:

    标签: bash command-line ls


    【解决方案1】:

    如果您可以使用while read 和管道创建的子进程,您可以:

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

    【讨论】:

    • 你甚至可以'find . -name '*.png' -exec echo {} \;'。如果需要,可以多次使用 find 的 -exec 选项。
    • 正确 - 对于一个命令(如此处的 echo),最好使用 -exec (或 |xargs 如果有很多文件,则性能更好)。对于多个命令,我更喜欢使用 while 循环。对我来说更容易阅读。干杯。
    【解决方案2】:

    另一种选择是更改 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 的更多信息。

    【讨论】:

      【解决方案3】:

      你可以试试,[[:space:]] 代替空格

      wdir="/Volumes/Development/My[[:space:]]Project/Project"
      

      或执行命令转换单个空格

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

      【讨论】:

        【解决方案4】:

        Use more quotesdon't parse ls output

        for image in "$wdir"/**/*.png; do
        

        【讨论】:

          猜你喜欢
          • 2010-10-10
          • 1970-01-01
          • 2015-06-09
          • 2012-11-08
          • 1970-01-01
          • 1970-01-01
          • 2014-09-07
          • 1970-01-01
          • 2020-07-22
          相关资源
          最近更新 更多