Help with ksh-to read ip file & append lines to another file based on pattern match

Hi,

I need help with this-
input.txt :
L B white
X Y white
A B brown
M Y black

Read this input file and if 3rd column is "white", then add specific lines to another file insert.txt.
If 3rd column is brown, add different set of lines to insert.txt, and so on.
For example, the given set of lines if 3rd column is white is
"*colors are random: yes
*colors are light: yes"

If 3rd column is brown, the lines to be appended are
"*colors are dark: no
*colors are random: no:

insert.txt is not empty, so the newly added lines have to be appended to end of file.
I prefer to have this in ksh.

Thanks!

Is this homework?
What do you have so far?

I have one which works but is not dependent on column3 in my input file.

while read col1 col2 col3
do
  my set of of instructions
done < input.txt

But when i edit the ksh script so that it matches 3rd column, it does not work.Also, I am not sure how to append to a file, once the column matches.
#!/bin/ksh
perl -e 'print "#Added for ...."' >> dir/my.txt

while read col1 col2 col3
do
echo $col3
if [["$col3"="white"]]; then
        print " matched"
else
        print "not matched"
fi
done < input.txt

The [[ ]] or the portable [ ] require spaces:

while read col1 col2 col3
do
echo $col3
if [ "$col3" = "white" ]; then
        print "white"
elif [ "$col3" = "brown" ]; then
        print "brown"
else
        print "not matched"
fi
done < input.txt

Please embed code in "code" tags! (Look at the top of the WIKI editor)

Try

while read col1 col2 col3 rest
   do
   case $col3 in
     (white) printf "%s\n%s\n" "*colors are random: yes" "*colors are light: yes";;
     (brown) printf "%s\n%s\n" "*colors are dark: no" "*colors are random: no:" ;;
     (*)     continue;;
   esac
   done <input.txt >>insert.txt
1 Like

Thanks for the replies.
The if loop with space worked.
And, for the 2nd part of my original question, I used "cat >> "to write into file.
Thanks again!

Yes >> is "append to file", but cat is not needed.

print "white" >> insert.txt

or, as Rudi suggested, redirect the output of the whole loop

while ...
do
...
done >> insert.txt
1 Like