tags:

views:

75

answers:

4

I'm trying to write a script the generates a template file for Pashua (a perl script for creating GUI on osx)

I want to crate an instance for each item in the array, so the ideal output would be:

AB1.type = openbrowser
AB1.label = Choose a master playlist file
AB1.width=310
AB1.tooltip = Blabla filesystem browser

AB2.type = openbrowser
AB2.label = Choose a master playlist file
AB2.width=310
AB2.tooltip = Blabla filesystem browser

...and so on for the rest of the array:

What I am using to write to the text file at the moment is:

count=1
saveIFS="$IFS"
IFS=$'\n'
array=($(<TEST.txt))
IFS="$saveIFS"
for i in "${array[@]}"; do declare AD$count="$i"; ((count++)); done
for i in "${array[@]}"; do echo "AD$count".type = openbrowser "AD$count".label = Choose   a master playlist file \n "AD$count".width=310 \n "AD$count".tooltip = Blabla filesystem browser \n" >> long.txt; done 

However \n doesn't produce a newline in the text file, and I am pretty sure there is a alot nicer way todo this, ideas?

+1  A: 

To use escape characters in an echo, statement, you must use echo -e. So, your code should look like this:

for i in "${array[@]}"; do echo -e "AD$count".type = openbrowser "AD$count".label = Choose   a master playlist file \n "AD$count".width=310 \n "AD$count".tooltip = Blabla filesystem browser \n" >> long.txt; done 
Dumb Guy
Excellent, thankyou
S1syphus
+1  A: 

The cleanest way is probably with a heredoc:

cat << EOF > out.txt
line 1
line 2
EOF
Ignacio Vazquez-Abrams
+1  A: 

Your first for loop creates a bunch of variables that you never use. Your second for loop does exactly the same thing on every iteration since it doesn't actually use $i or any of the $ADn variables that you created.

Since you haven't shown what's in your text file, it's hard to know what you're trying to accomplish, but here's a stab at it:

count=1
saveIFS="$IFS"
IFS=$'\n'
array=($(<TEST.txt))
IFS="$saveIFS"
for i in "${array[@]}"
do
    echo "AB${count}.type = openbrowser"
    echo "AB${count}.label = Choose a master playlist file"
    echo "AB${count}.width=310"
    echo "AB${count}.tooltip = Blabla filesystem browser"
    echo "some text with a line from the file: $i"
    (( count++ ))
done >> long.txt

But if you're doing something like that, you don't need an array:

count=1
while read -r i
do
    echo "AB${count}.type = openbrowser"
    echo "AB${count}.label = Choose a master playlist file"
    echo "AB${count}.width=310"
    echo "AB${count}.tooltip = Blabla filesystem browser"
    echo "some text with a line from the file: $i"
    (( count++ ))
done < TEST.txt >> long.txt
Dennis Williamson
+1  A: 

Read from an here doc an replace expand count variable i:

# Your array 
a=(1 2 3 4 5 10)

for i in ${a[@]}; do cat <<EOF
AB${i}.type = openbrowser
AB${i}.label = Choose a master playlist file
AB${i}.width=3${i}0
AB${i}.tooltip = Blabla filesystem browser

EOF
done
Jürgen Hötzel