Insert blank line if grep not found

Hi all,

I've googling around forum regarding my prob, the nearest would same as thread tittled Insert blank line if grep not found, but she/he did not mention the solution, so I would like to request your help

I've this task, to search in file2 based on pattern in file1 and output it to file3. If the pattern is not found I want it to put it as blank line in file3.

file1

ACGTGCAT
ACGGTACG
CGTGATGC
GTAGCAGT
GGCATGCT
GTGACGTA

file2

ACGTGCAT      34
GGCATGCT      54
GTGACGTA      24

output (file3)

ACGTGCAT     34
<blank line>
<blank line>
<blank line>
GGCATGCT     54
GTGACGTA     24

I've been trying using this command

for f in `cat file1` ; do grep "$f" file >> file3 ; done

but it dont keep blank space. I want to have result as file3 (shown above) so I can paste back to file1 and it show the same sequence position.

thanks in advance

while read line1
do
    line2=`grep "$line1" file2`
    if [ ! -z "$line2" ] ; then
        echo "$line2" >> file3
    else
        echo "" >> file3
    fi
done < file1
2 Likes

Hi Rohon,

Superb!! :b::b: Exactly as i want.

Thanks, you saved my day

1 Like
 
awk 'NR==FNR{a[$1]=$0;next;}{if(a[$1]) print a[$1];else print "";}' file2 file1 > file3

wrong message