T
Task2mo ago
Aco-gt

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.
task: Failed to run task "sample-for-cmd": 6:1: "foo(" must be followed by )
task: Failed to run task "sample-for-cmd": 6:1: "foo(" must be followed by )
Here is the relevant part of my Taskfile:
sample-for-cmd:
desc: Sample how to use for cmd
vars:
PDF_PATH: "./my_pdf_path"
DEST_PATH: "./my_dest_path"
MY_VAR:
sh: find {{.PDF_PATH}} -type f -name *.pdf
cmds:
- for: { var: MY_VAR, split: '\t' }
cmd: cp {{.ITEM}} {{.DEST_PATH}}
sample-for-cmd:
desc: Sample how to use for cmd
vars:
PDF_PATH: "./my_pdf_path"
DEST_PATH: "./my_dest_path"
MY_VAR:
sh: find {{.PDF_PATH}} -type f -name *.pdf
cmds:
- for: { var: MY_VAR, split: '\t' }
cmd: cp {{.ITEM}} {{.DEST_PATH}}
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
andreynering
andreynering2mo ago
Hi @Aco-gt, Can you try using the shellQuote (aliases to q) template function? {{shellQuote .ITEM}} or {{q .ITEM}}
Aco-gt
Aco-gt2mo ago
Hi @andreynering , Thanks to your advice, it worked perfectly. However, the find part ended up being quite a tricky method.
sample-for-cmd:
desc: Sample how to use for cmd
vars:
PDF_PATH: "documents/pdf_files"
MY_VAR:
sh: find {{.PDF_PATH}} -type f -name *.pdf -print0 | tr '\0' '@'| head -c -1
cmds:
- for: { var: MY_VAR, split: '@' }
cmd: ls {{ shellQuote .ITEM}}
sample-for-cmd:
desc: Sample how to use for cmd
vars:
PDF_PATH: "documents/pdf_files"
MY_VAR:
sh: find {{.PDF_PATH}} -type f -name *.pdf -print0 | tr '\0' '@'| head -c -1
cmds:
- for: { var: MY_VAR, split: '@' }
cmd: ls {{ shellQuote .ITEM}}
$ 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 @.
Want results from more Discord servers?
Add your server