Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem Listing files in bash with spaces in directory path

When entered directory into the command line, this:

ls -d -1 "/Volumes/Development/My Project/Project"/**/* | grep \.png$

Prints a list of all the file ending in .png.

However when I try and create a script:

#! /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

The space is causing an issue, but I don't know why?

like image 381
Richard Stelling Avatar asked Aug 01 '11 10:08

Richard Stelling


People also ask

How do you handle spaces in Bash?

Filename with Spaces in Bash A simple method will be to rename the file that you are trying to access and remove spaces. Some other methods are using single or double quotations on the file name with spaces or using escape (\) symbol right before the space.

How do I use file paths with spaces?

Use quotation marks when specifying long filenames or paths with spaces. For example, typing the copy c:\my file name d:\my new file name command at the command prompt results in the following error message: The system cannot find the file specified. The quotation marks must be used.

How do I list files in a directory in Bash?

To see a list of all subdirectories and files within your current working directory, use the command ls . In the example above, ls printed the contents of the home directory which contains the subdirectories called documents and downloads and the files called addresses.

Can Linux paths have spaces?

In the Linux operating system, we can run commands by passing multiple arguments. A space separates each argument. So, if we give the path that has a space, it will be considered two different arguments instead of one a single path.


2 Answers

If you fine with using while read and subprocess created by pipe, you can:

find . -name '*.png' | while read FILE
do 
    echo "the File is [$FILE]"
done
like image 79
Michał Šrajer Avatar answered Nov 15 '22 09:11

Michał Šrajer


Use more quotes and don't parse ls output.

for image in "$wdir"/**/*.png; do
like image 26
l0b0 Avatar answered Nov 15 '22 08:11

l0b0