Nothing I've tried works. Look at the grep to array lines in the script below. Escaping seems to do nothing. But if I make a statically assigned array It's fine.
Such as:
files=(somefile.txt
some\ other\ file.pdf
"yet another file.txt")
This does not work:
#!/bin/bash
find . -name "$1" |
(
cat - > /tmp/names
file -N --mime-type --files-from /tmp/names
) |
(
cat - > /tmp/mimes
# files=("$(grep -o '^[^:]*' /tmp/mimes)") #one element array
# files=($(grep -o '^[^:]*' /tmp/mimes)) #files with spaces end up split in to several elements
# files=($(grep -o '^[^:]*' /tmp/mimes | sed 's/ /\\ /g')) #same but with \ terminated strings
files=($(grep -o '^[^:]*' /tmp/mimes | cat <(echo '"') - <(echo '"')))
mimes=($(grep -o '[^:]*$' /tmp/mimes))
total=${#files[*]}
for (( i=0; i<=$(( $total -1 )); i++ ))
do
echo Mime: "${mimes[$i]}" File: "${files[$i]}"
done
printf "$i\n"
)
Edit: Clarification
file /tmp/mimes contains:
./New Text.txt: text/plain
If I grep it to get every thing before the ":"
grep -o '^[^:]*' /tmp/mimes
it outputs: ./New Text.txt
I want to put this output into an array, but it has a space, so I escape the space using sed.
files=($(grep -o '^[^:]*' /tmp/mimes | sed 's/ /\\ /g'))
This does not work. I end up with files[0] = "./New\" and files[1] = "Text.txt"
My question is why doesn't escaping the space work?
If I do:
files=(./New\ Text.txt)
It does work however files[0] = "./New Text.txt" Why does escaping when you do it manually work but when it's the output of grep and sed it doesn't work. It seems like the behaviour of creating an array is inconsistent.