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

I have two files: file1.txtand file2.txt. Each of them has the same number of lines, but some of the lines file1.txtare empty. This is easiest to see when the contents of two files are displayed in parallel:

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

I need to put these files together so that empty lines in are file1.txtfilled with data found in lines (of one line number) from file2.txt. The result in file3.txtwill look like this:

cat
fish
spider
snail
catfish
snake
koala
rabbit

, , - while read -r line, , , while , if-conditional, , $line , cut, file2.txt . .

  • file2.txt . file1.txt , file2.txt , file3.txt.

?

+4
6
paste file1.txt file2.txt | awk -F '\t' '$1 { print $1 ; next } { print $2 }'
+4

awk:

awk 'FNR==NR {a[NR]=$0;next} {print (NF?$0:a[FNR])}' file2 file1
cat
fish
spider
snail
catfish
snake
koala
rabbit

file2 a,
file1, itst, file1
, , file2

+4

getline ( ):

awk '{getline p<f; print NF?$0:p; p=x}' f=file2 file1
+2

:

paste file1.txt file2.txt | sed -E 's/^   //g' | cut -f1

, (, 1), .

( OSX \t sed, , TAB, ctrl-V, Tab)

+1

Bash.

for i in 1 2; do
    while read line; do
        if [ $i -eq 1 ]; then
            arr1+=("$line")
        else
            arr2+=("$line")
        fi
    done < file${i}.txt
done
for r in ${!arr1[@]}; do
    if [[ -n ${arr1[$r]} ]]; then
            echo ${arr1[$r]}
    else
            echo ${arr2[$r]}
    fi
done > file3.txt
+1

awk:

paste -d"#" file1 file2 | sed 's/^#\(.*\)/\1/' | cut -d"#" -f1
+1

Source: https://habr.com/ru/post/1529519/


All Articles