ehime
ehime

Reputation: 8375

Issues in spaced filepaths with complex find loop

Title should say it all, if not let me know and I will update the question.

The code

TYPE=('html?' 'jsp' 'php')
TYPE=$(printf "|%s" "${TYPE[@]}")

## will not except paths with spaces
for file in $(find -E * -type f -iregex ".*(${TYPE:1})") ; do 
    echo $file
done

While trying to wrap it

## command substitution: line ~: syntax error near unexpected token `('
## command substitution: line ~: `find -E * -type f -iregex \".*(${TYPE:1})\")"'
for file in "$(find -E * -type f -iregex \".*(${TYPE:1})\")" ; do 
    echo $file
done

Upvotes: 0

Views: 27

Answers (1)

konsolebox
konsolebox

Reputation: 75488

You're quoting it wrong. Proper way is:

for file in $(find -E * -type f -iregex ".*(${TYPE:1})"); do 

But if you're using bash the better way is to use a while loop with process substitution:

while IFS= read -r file; do
    echo "$file"
done < <(exec find -E * -type f -iregex ".*(${TYPE:1})")

find -E * -type f -iregex ".*(${TYPE:1})" | while IFS= read -r file; do may apply too but it runs your loop on a subshell. Changes in variables are lost after it exits.

Also if you're using Bash 3.1 or newer, you can just use -v option of printf:

printf -v TYPE '|%s' "${TYPE[@]}"

Upvotes: 1

Related Questions