Bash shell script not working-picking segment patterns from a file

Hi All,

I have to pick particular segments from a file and I have prepared below shell script.But its not working and I am not able to find out whats the issue.could you guys pls help?
Sample file:

TS3*1451575*12*20151231*4*482.44
NM1*QC*1*CUTLER*BETTY
DTM*472*20150808
REF*6R*00000802960404783585
NM1*QC*1*CUTLER*BETTY
DTM*472*20150808
REF*6R*00000802960301783584
NM1*QC*1*POWELL*XYZ
DTM*472*20150808
REF*6R*00000802905105783586
NM1*QC*1*QUIRING*ROBERT
DTM*472*20150808
REF*6R*00000803057901783583
TS3*1459088*12*20151231*2*156.8
NM1*QC*1*VENABLE*DAVID
DTM*472*20150808
REF*6R*00000882310302783651
NM1*QC*1*WHITING*SHERRY
DTM*472*20150808
REF*6R*00000882461300783652
 
Script:
#!/bin/sh
 
echo "Please enter file name"
 
read file
 
 
set first = ""
set second = ""
set third = ""
set fourth = ""
set fifth = ""
 
 
while read line
 
do
 
line_check=$(echo $line|awk -F"\*" '{print $1}')
if [ $line_check == "TS3" ]
 
then
 
set first  =  $line
 
elif [ $line_check = "CLP" ]
 
then
 
set second = $line
 
 
elif [ $line_check = "NM1" ]
 
then
 
set third = $line
 
 
elif [ $line_check = "DTM" ]
 
then
 
set fourth = $line
 
 
else [ $line_check = "REF*" ]
 
set fifth = $line
 
if [ $first != " -a $second != "" -a $third != "" -a $fourth != "" -a $fifth != "" ]
then
echo $first >> newfile.txt
echo $second >> newfile.txt
echo $third  >> newfile.txt
echo $fourth >> newfile.txt
echo $fifth  >> newfile.txt
 
set first = ""
set second = ""
set third = ""
set fourth = ""
set  fifth = ""
 
fi
fi
done < $file
 
 

If you have GNU grep available to you the following performs the required check

#!/bin/sh

echo "Please enter file name"

read filename

egrep -no '^TS3|^NM1|^DTM|^REF|^CLP' filename

Thanks for the help.but egrep is not available on this machine.

btw Do you see any syntax errors in my script?

try grep -e ?

the issue is that you're attempting to read the file from STDIN, you're also re-writing a very specific instance of grep.

What exactly is "not working"? Error messages? Empty result files? Dth. else?

---------- Post updated at 19:29 ---------- Previous update was at 19:19 ----------

Plus, what system & shell are you using?