Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fill empty lines from one file with corresponding lines from another file, in BASH?

Tags:

bash

awk

cut

I have two files, file1.txt and file2.txt. Each has an identical number of lines, but some of the lines in file1.txt are empty. This is easiest to see when the content of the two files is displayed in parallel:

file1.txt     file2.txt
cat           bear
fish          eagle
spider        leopard
              snail
catfish       rainbow trout
              snake
              koala
rabbit        fish

I need to assemble these files together, such that the empty lines in file1.txt are filled with the data found in the lines (of the same line number) from file2.txt. The result in file3.txt would look like this:

cat
fish
spider
snail
catfish
snake
koala
rabbit

The best I can do so far, is create a while read -r line loop, create a counter that counts how many times the while loop has looped, then use an if-conditional to check if $line is empty, then use cut to obtain the line number from file2.txt according to the number on the counter. This method seems really inefficient.

  • Sometimes file2.txt might contain some empty lines. If file1.txt has an empty line and file2.txt also has an empty line in the same place, the result is an empty line in file3.txt.

How can I fill the empty lines in one file with corresponding lines from another file?

like image 927
Village Avatar asked Dec 12 '22 07:12

Village


1 Answers

paste file1.txt file2.txt | awk -F '\t' '$1 { print $1 ; next } { print $2 }'
like image 132
Ignacio Vazquez-Abrams Avatar answered May 10 '23 14:05

Ignacio Vazquez-Abrams