Insert blank line if grep not found

Hello everyone... please help if you can -- I'm stumped. Making this work will save me hours of manual labor:

I need to search file2 for pattern in file1. If pattern found append file2 line to file3. If pattern not found append a blank line to file3.

file1 contents example:

123
456
789
101
121

file2 contents example:

123 Joe
456 Man
101 Rob

I need to end up with a file3 that looks like this:

123 Joe
456 Man
<blank line>
101 Rob
<blank line>

I tried this:

grep -f file1 file2 >> file3 || print "\n" >> file3

Can you think of a way that works???
Any help would be GREATLY appreciated!

cat file1 | while read line
do grep $line file2 >> file3

if [ $? -eq 1 ]
then
print "\n" >> file3
fi
done

This still only gives me a file3 of:
123 Joe
456 Man
101 Rob

I need to account for the fact that 789 and 121 of file1 were not found in file2.

Thanks again...

Hmm, curiously this same problem has already been asked and answered once before! See this thread

Also, please see the rules about searching before you post. By the way, is this a homework assignment?

I did do extensive searching here to no avail... I found many variations, but none that inserted a blank line if not found. In fact, in reviewing the thread you linked I still don't see the answer. I am a bit sleep deprived since we've been working around the clock to get ready for registration at the college I work for... so I do apologize... but please help just the same. (smile)

This is not homework... I am the acting system administrator (newbie) at a Saint Augustine's College in Raleigh, NC.

I need this file to help the business office compare a list of students who have pre-registered for classes to a list of students who have been awarded financial aid. This way they will know which students have enough aid to pay for classes without manually researching each students account.

Again, thanks again for your reply.

Lorrinda S. Michieka

You seem to have a couple of theories about what you want. Your second post seems to solve the problem posed by your first post more or less.

What shell are you using? What system? You should control which shell runs your script with a line like:
#! /usr/bin/ksh
as the first line.

You don't want to print "\n"; just use print. It adds a new line automatically.

That cat process is not doing anything useful. Open the file with exec and then start reading it:
exec < file
while read line

grep will set $? to 1 if there were no matches so you should be ok if you run the script as you posted it...no lines after the grep and before the if.

Taking out the blank line between grep and if did the trick. Thanks so much. I'm using AIX and the korne shell.

Happy New Year... (indeed!)

Well I'm happy if you're happy! :slight_smile:

But a blank line should have been ok. I was worried about a line like, oh,:
echo after grep val = $? > /dev/tty

In this case the echo statement itself would set $? to 0 since the echo worked.