How to use for loop with filenames containing spaces?
I'm encountering an error when trying to run a Taskfile and need some help.
My task needs to process filenames that may contain spaces.
Here is the relevant part of my Taskfile:
However, it doesn't seem to work correctly when filenames contain spaces.
I tried using tr to convert null characters to tabs,
find {{.PDF_PATH}} -type f -name '*.pdf' -print0 | tr '\0' '\t'
but it still didn't work.
Does anyone know how to correctly use the for loop with filenames containing spaces in Taskfile?
Thanks!
2 Replies
Hi @Aco-gt,
Can you try using the
shellQuote
(aliases to q
) template function?
{{shellQuote .ITEM}}
or {{q .ITEM}}
Hi @andreynering ,
Thanks to your advice, it worked perfectly. However, the find part ended up being quite a tricky method.
$ ls documents/pdf_files
a-sample.pdf 'b sample.pdf' 'c sample d.pdf'
$ task sample-for-cmd
task: [sample-for-cmd] ls 'documents/pdf_files/b sample.pdf'
'documents/pdf_files/b sample.pdf'
task: [sample-for-cmd] ls documents/pdf_files/a-sample.pdf
documents/pdf_files/a-sample.pdf
task: [sample-for-cmd] ls 'documents/pdf_files/c sample d.pdf'
'documents/pdf_files/c sample d.pdf'
Explanation
find {{.PDF_PATH}} -type f -name "*.pdf" -print0: Finds all PDF files in the specified path and outputs the filenames separated by a NULL character (\0).
tr '\0' '@': Translates NULL characters (\0) to the @ symbol.
head -c -1: Removes the last character, which is the trailing @.
This command sequence effectively lists the PDF files with @ as the delimiter and removes the unnecessary trailing @.