user3048888 user3048888 - 5 months ago 13
Bash Question

Bash script with using special characters in variable array and copy to folder

I've a new question about a closed question from me.
In the last one I asked for help in fixing a script, which sorts files to folders by it's content. (Bash script which sorts files to folders by it's content; How to solve wildcard in variables?)

Now I have a new problem with that.
The variables had changed. The old ones where single word variables in an array, now I've multiple words with special characters as variable.

Here is my script:

#!/bin/bash
declare -a standorte;
standorte=('Zweigst: 00' 'Zweigst: 03' 'Zweigst: 08')

ls lp.3.* | while read f
do
for ort in "${standorte[@]}"; do
grep -i $ort "$f" >/dev/null 2>&1
if [ $? -eq 0 ]; then
echo Copying $f to $ort
cp "$f" $ort
fi
done
done


Now you see, the "ort" is the folder name. So the script try to copy the file lp.3.* to e.g. Zweigst: 00. But without the escape backslashes it doesn't work. Put I escape charakters into the variable, the script doesn't work, because in the file lp.3.* is no "Zweigst\:\ 00".

I think, I must declare a new variable for "ort" where I put the folder names in it.
But I've no idea how to change the for loop. I must say the script, when you found Zweigst: 00 copy this file to folder "zweigst00". I'm sorry my bash script experience is not good at all. I can't change this by my own.

I have multiple (zero to unlimited) lp.3.* files (e.g. lp.3.1, lp.3.2, lp.3.5.2 and so on)
In this files is this text: http://pastebin.com/0ZzCUrpx

Answer

You just need to quote the variable:

for ort in "${standorte[@]}"; do
   grep -i "$ort" "$f" >/dev/null 2>&1
#          ^----^-------- quotes needed
   if [ $? -eq 0 ]; then
      echo Copying $f to $ort
      cp "$f" "$ort"
#             ^----^-------- quotes needed
   fi
done

Why? Because otherwise this

grep -i $ort "$f" >/dev/null 2>&1

gets expanded as something that grep cannot understand properly:

grep -i Zweigst: 00 "$f" >/dev/null 2>&1

see that it is trying to grep Zgeigst: from file 00.