tags:

views:

50

answers:

3

Hi,

I getting space delimited list of titles based on this code:

TITLES=`awk -F'|' '{print $1}' titles.txt | cut -d'=' -f2 | sort

Then I use that list in a for loop to print out the results:

for T in $TITLES
do
     echo "$T"
done

The problem is that when a title has more than one word and the words are separated by a space then my for loop prints them out as separate things.

I tried adding double qoutes using sed to each title but that just caused the loop to print each word in double quotes rather then the two word titles together.

How can I fix this?

+2  A: 

Have you tried putting quotes around $TITLES?

TITLES=`awk -F'|' '{print $1}' titles.txt | cut -d'=' -f2 | sort`
for T in "$TITLES"
do
    echo "$T"
done

Or you could use while:

awk -F'|' '{print $1}' titles.txt | cut -d'=' -f2 | sort | while read T
do
    echo "$T"
done
Mark Byers
this code gives me "Error 500"
goe
Sorry, I missed a do. Try again.
Mark Byers
this will probably work in the unix console but I need to run this in a script and instead of echo I will eventually have a variable inside that loop and use it outside of the loop. This scenario doesn't work for me right now.
goe
All I did was copy your code and fix it so that it correctly handles spaces. If your code doesn't do what you want it to do, perhaps you could tell us what you actually want in the question. Also how can you have a variable inside the loop that you use outside the loop?
Mark Byers
I added a different suggestion.
Mark Byers
+1  A: 

One way to do this is to set IFS:

IFS='
'
for T in $(awk -F'|' '{print $1}' titles.txt | cut -d'=' -f2 | sort)
do
     echo "$T"
done

This sets IFS to just newline (there's a newline between the open and close single-quotes).

I know this works in bash, but I'm not sure how portable it is to other shells.

If you do this you'll almost certainly want to set IFS back to its old value once you're done the loop.

Laurence Gonsalves
This works!!! OK, how can I set the IFS back to the old value then after the loop is done?
goe
It's normally space tab and newline, so you can either set it that way explicitly, or you could store the old value in a temp variable before the loop, and then restore the value of IFS from the temp variable after the loop.
Laurence Gonsalves
That's a good idea, thanks!
goe
Readability can be improved by using `IFS=$'\n'`
Dennis Williamson
A: 

hi you could use the shell without external tools

while IFS="|" read -r a b
do
    IFS="="
    set -- $a
    T=$2
    echo "T is $T"
    unset IFS
done <"file"