while loop stops after a function...

my ksh script is not working...
i wanna remove lines in file2.txt from file1.txt

# cat file1.txt
this is line one 
this is line two
this is line three
this is line four
this is line five

# cat file2.txt
this is line two
this is line three

# cat my_script.ksh
#!/bin/ksh

i=1
y=1
myfunc()
{
exec < file1.txt
while read line ; do
file1=$line
if [[ ${file1} = ${arr2[y]} ]] ; then
echo ${file1} and ${file2[y]} are the same.
sed ''$i'd' file1.txt > new.txt
mv new.txt file1.txt
else
echo ${file1} and ${file2[y]} are not the same.
fi
(( i=i+1 ))
done
return
}
exec < file2.txt
while read line2 ; do
file2[y]=$line2
myfunc     # calling the function
(( y=y+1 ))
done
cat file1.txt

the output is:

this is line one
this is line three
this is line four
this is line five

yes... the problem is while loop stops right after the function ends...

i can't reply anymore.... so i just add more here.

thanx balajesuri!!!
that works! what a simple solution!
however its not really matching line deleting...
what if i have a line "this is line two and extra"
grep -v -f file2.txt file1.txt deletes that line...

  1. What're you trying to achieve?
  2. What is the desired output from file1.txt and file2.txt?

i want to delete matching lines in file2.txt from file1.txt
so my desired file1.txt output is

this is line one
this is line four
this is line five

A simple grep should do:

grep -v -f file2.txt file1.txt

---------- Post updated at 13:37 ---------- Previous update was at 12:45 ----------

  1. You have "this is line two and extra" in which file. file1.txt or file2.txt?
  2. And why can't you reply anymore? Please don't edit earlier posts. Other members might not be able to track.

what if i have a line "this is line two and extra" in file1.txt, then your code will delete that line.
i want to remove lines that matching exactly to lines in file2.txt
thanx again

The grep man-page shows you what options you have. In your case this should do:

grep -vxf file2.txt file1.txt

"grep -vxf file2.txt file2.txt" worked perfectly!!! really appreciate it!!!
but do you see any problems in my script why main loop stops reading in after the myfunc anyways? :slight_smile:

You redirect file2.txt to stdin and start to read from it in a loop. Every iteration of that loop you call your function that redirects file1.txt to stdin. Functions usually do not start a subshell, so stdin is still file1.txt after you return from your function.

yeah that really make sense!!! thanks!!!