Solved sed: add to end of line w/variable in pattern

May 19, 2011 at 08:36:05
Specs: rhel, lots
Hi All,

I'm trying to match a word (a color) in a description field of a csv and if I find this color, add it to the end of a line (creating a new column). The color is actually a list of colors stored in a variable. I need to do this line by line.

The problem I'm having is that I think it's only ever reading the first value in $COLORS. Can someone see what I'm doing wrong?

Thanks!

IFS=$';'

COLORS="BLACK;BROWN;WHITE;BEIGE;GRAY;GREY;RED;TAUPE;CHOCOLATE BROWN;WHITE-PERIWINKLE/BONE"

cat $INFILE.in | while read line
do
for color in $COLORS
do
grep $color |sed "s/$/,$color/g"
done
done

#END OF SCRIPT

#INFILE EXAMPLE
y,something,something,something,there is a color like BLACK here,something
y,something,something,something,there is a color like BROWN here,something
y,something,something,something,there is a color like WHITE here,something


See More: sed: add to end of line w/variable in pattern

Report •

#1
May 19, 2011 at 10:17:50
✔ Best Answer
The key here is that setting the field seperator, IFS, at the top of the script messes up the while loop.

Note that I am saving the IFS and changing it only for the for loop iteration and then restoring it.

If it were me, I'd set up the COLORS variable so I could delimit the colors by spaces, if I could, so I wouldn't have to mess with IFS:

#!/bin/ksh

COLORS="BLACK;BROWN;WHITE;BEIGE;GRAY;GREY;RED;TAUPE;CHOCOLATE BROWN;WHITE-PERIWINKLE/BONE"

INFILE="infile"
while read line
do
   OLDFS="$IFS"
   IFS=";"
   for color in $COLORS
   do
      if echo "$line"| grep "$color" > /dev/null 2>&1
      then
         echo "$line"| sed 's/$/,'"${color}"'/g'
      fi
   done
   IFS="$OLDFS"
done < $INFILE.in


Report •

#2
May 19, 2011 at 10:49:33
Ah! Yes I had to put IFS in there because some of the colors include a space unfortunately.

This works great! Thank you so much for your assistance!


Report •
Related Solutions


Ask Question