通过awk / xargs替换定义的字符串中的变量值

问题描述 投票:2回答:1

我们正在bash中动态生成一个字符串以在oracle数据库中插入数据。字符串就像

> echo $str1
insert into tbl select '$jobid','$1','$2','$3','$sdate' from dual ; 

这里变量$ 1,$ 2 ...是动态的,最多可以增加到10

现在我们在文件中有相同数量的':'分隔数据列,因为上面的字符串中有数字变量($ 1,$ 2 ..)。

这里的挑战是将$ 1替换为第一列数据,$ 2替换为第二列,依此类推。这需要针对数据集的所有行进行,并且需要使用“插入”字符串作为基础并使用文件中的替换数据来生成单独的文件。

例如用于示例数据

cat test.dat
ONLINE:odr1_redo_06a.log:NO
ONLINE:odr1_redo_06b.log:NO
ONLINE:odr1_redo_05a.log:NO

and the string is 
echo $str1
insert into tbl select '$jobid','$1','$2','$3','$sdate' from dual ;

必需的输出应该是

insert into tbl select '$jobid','ONLINE','odr1_redo_06a.log','NO','$sdate' from dual ;
insert into tbl select '$jobid','ONLINE','odr1_redo_06b.log','NO','$sdate' from dual ;
insert into tbl select '$jobid','ONLINE','odr1_redo_05a.log','NO','$sdate' from dual ;

[使用字符串作为awk中的外部变量。没运气

cat test.dat | awk -F: -v var="$str1" '{print var}'
insert into tbl select '$jobid','$1','$2','$3','$sdate' from dual ;
insert into tbl select '$jobid','$1','$2','$3','$sdate' from dual ;
insert into tbl select '$jobid','$1','$2','$3','$sdate' from dual ;

or xargs
sed 's/:/ /g' test.dat | xargs -n3 bash -c "echo $str1"
insert into tbl select $jobid,$1,$2,$3,$sdate from dual
insert into tbl select $jobid,$1,$2,$3,$sdate from dual
insert into tbl select $jobid,$1,$2,$3,$sdate from dual

编写一个小循环并逐行调用会产生开销,因此不希望这样做。任何想法如何以最佳方式完成此操作?

unix awk xargs
1个回答
0
投票

使用Awk:

awk -F: -v tmpl="$str" '{
  out = tmpl
  for (i=1; i<=NF; i++)
    gsub(("\\$" i), $i, out)
  print out
}' file

概念证明:

$ str="insert into tbl select '\$jobid','\$1','\$2','\$3','\$sdate' from dual ;"
$
$ awk -F: -v tmpl="$str" '{
>   out = tmpl
>   for (i=1; i<=NF; i++)
>     gsub(("\\$" i), $i, out)
>   print out
> }' file
insert into tbl select '$jobid','ONLINE','odr1_redo_06a.log','NO','$sdate' from dual ;
insert into tbl select '$jobid','ONLINE','odr1_redo_06b.log','NO','$sdate' from dual ;
insert into tbl select '$jobid','ONLINE','odr1_redo_05a.log','NO','$sdate' from dual ;
© www.soinside.com 2019 - 2024. All rights reserved.