system
1
Hi, Gurus,
I got a problem to resolve following issue:
I have one file file1as following:
[title1]
start_dt=2010-01-01 12:00:02
[title2]
start_dt=2011-01-01 09:00:02
[title3]
start_dt=2009-01-01 11:00:02
I have another file file2 as following:
title1, 2010-01-03 10:00:02
title2, 2011-01-04 11:00:02
title3, 2009-02-04 13:00:02
I need replace file1's start_dt value with file2's value based on title value. final file should like following:
[title1]
start_dt=2010-01-03 10:00:02
[title2]
start_dt=2011-01-04 11:00:02
[title3]
start_dt=2009-02-04 13:00:02
:wall:
Could any one among you may able to help please ?
Thanks in advance
sk1418
2
this would be what you need:
awk -F, 'NR==FNR{ a["["$1"]"]=$2} NR>FNR{ if($0 in a){ f =1;i=$0; print $0; next;}else{ $0 = "start_dt="a; print $0; f=0;i=0; } }' file2 file1
output:
[title1]
start_dt= 2010-01-03 10:00:02
[title2]
start_dt= 2011-01-04 11:00:02
[title3]
start_dt= 2009-02-04 13:00:02
The solution will not work for the following data:
File1:
[title1]
start_dt=2010-01-01 12:00:02
[title2]
start_dt=2011-01-01 09:00:02
[title3]
start_dt=2009-01-01 11:00:02
[title9]
start_dt=2011-01-01 07:00:02
File2:
title2, 2010-01-03 10:00:02
title3, 2011-01-04 11:00:02
title7, 2009-02-04 13:00:02
system
4
Thanks, sk1418,
after I change awk to nawk (since my OS is sun sparc) it works perfectly.
sk1418
5
OK, corrected version comes:
awk -F, 'NR==FNR{ a["["$1"]"]=$2}
NR>FNR{ if($0 in a){
f =1;i=$0; print $0; next; }
if(f==1&&i){
$0 = "start_dt="a;
print $0; f=0;i=0; }else print $0 }' file2 file1
output based on your example:
[title1]
start_dt=2010-01-01 12:00:02
[title2]
start_dt= 2010-01-03 10:00:02
[title3]
start_dt= 2011-01-04 11:00:02
[title9]
start_dt=2011-01-01 07:00:02
nawk 'BEGIN {
while (getline < "./file1" > 0)
if ($0 ~ "title") {
gsub("\[|\]","",l=$0)
x[l]=$0
while (getline s < "./file1" > 0)
if (s ~ "start_dt=") {
split(s,a,"=")
y[l] = a[1]
z[l] = a[2]
break
}
}
} {
FS=", "
if ($1 in x)
printf("%s\n%s=%s\n", x[$1],y[$1],$2)
}' ./file2