Im working on a bit of automation and I’m a bit stuck at this one point. I have came up with several different ways of listing out just files, or just folders of a particular directory.
The simplest being:
for f in $(find ${source_path} -maxdepth 1 -type f); do echo "${f}"; done
The problem is when the list is read, files with spaces are appearing as if a new line is added in between each space.
Ex:
/path/There
were
several
confirmations
with
united.docx
/path/gfw_list.txt
/path/Emergency_Action_Plan.docx
/path/FirstName
LastName
OL
021015.docx
/path/7temp_disp.docx
In the above example FirstName LastName OL 021015.docx & There were several confirmations with united.docx are the real file names but are given several individual lines.
How can I create a list of all of the files (including the ones with spaces). I would imagine this same thing would happen when I list out folders but I haven’t ran into it just yet. I’d also potentially be looking for an absolute path for the output.
>Solution :
Without double quotes around the $(find ...) you get word splitting, ie, the for f sees all spaces as filename separators.
Wrapping the $(find ...) in double quotes disables the word splitting and allows the for f to process files with embedded spaces.
Setup:
$ touch 'a b c.txt'
Without double quotes:
$ for f in $(find . -name '*.txt'); do echo "${f}"; done
./a
b
c.txt
With double quotes:
$ for f in "$(find . -name '*.txt')"; do echo "${f}"; done
./a b c.txt
NOTE: if ${source_path} could contain spaces then the current find will also suffer from word splitting; in that case you’ll also want to wrap ${source_path} in double quotes, ie, change find ${source_path} ... to find "${source_path}" ...