cplus
cplus

Reputation: 1115

bash script replace all null values in a file by lines from another file

I have two files:

File1.sql

here is the few first lines:

insert into comment (id, field1, field2, field3, date) values (8001, 13, 44, null, '2007-07-06 02:48:15');
insert into comment (id, field1, field2, field3, date) values (8002, 18, 738, null, '2008-12-23 16:30:17');
insert into comment (id, field1, field2, field3, date) values (8003, 3, 150, null, '2007-06-07 06:27:52');

and another file2.txt:

'this is test'
'another example'
'third one'

they both have the same number of lines. I want to replace null string in file1.sql, we have only one null in each line, with the corresponding line from the other file2.txt

How can I do it in sed or awk?

update

OLD="null"
NEW="abc"

sed -i 's/$OLD/$NEW/g' file.txt

this is my try, but very basic and cannot go further.

Upvotes: 0

Views: 790

Answers (1)

James Brown
James Brown

Reputation: 37454

In awk, pretty much complete rewrite as & in a[FNR] when using sub causes problems.

$ awk '
NR==FNR { a[FNR]=$0; next }        # hash the records to a
{ 
for(i=1;i<=NF;i++)                 # iterate every field
    if(tolower($i)~/^null,?$/) {   # if its null (or null,)
        $i=a[FNR]($i~/,$/?",":"")  # replace it
        break                      # only once 
    }
}1' file2.txt File1.sql
insert into comment (id, field1, field2, field3, date) values (8001, 13, 44, 'this is test', '2007-07-06 02:48:15');
insert into comment (id, field1, field2, field3, date) values (8002, 18, 738, 'another example', '2008-12-23 16:30:17');
insert into comment (id, field1, field2, field3, date) values (8003, 3, 150, 'third one', '2007-06-07 06:27:52');

Upvotes: 1

Related Questions