我正在开发一个脚本,该脚本必须采用以下格式的文本文件:field1 @ field2 @ 20200101133030 @ field4,我需要将其转换为sql插入命令。出色地。第三个字段是日期。我有一个将日期转换为to_date('2020/01/01:13:30:30','yyyy / mm / dd:hh24:mi:ss')的脚本,
funcion(){
echo $1 | nawk -v s1="\047" -v firstPart="to_date(" -v lastPart="yyyy/mm/dd:hh24:mi:ss" '
{
print firstPart s1 substr($0,1,4) "/" substr($0,5,2) "/" substr($0,7,2)":"\
substr($0,9,2)":"substr($0,11,2)":"substr($0,13,2) s1 ", " s1\
lastPart s1 ")"
}'
}
我还有另一个脚本将整个行拆分为一个插入命令:
createInsert(){
echo $1 | awk -F'@' '{
printf "INSERT INTO myTable VALUES (\x27%s\x27,\x27%s\x27,\x27%s\x27,\x27%s\x27,\x27%s\x27,\x27%s\x27,\x27%s\x27);",$1,$2,$3,$4,$5,$6,$7;print ""
}'
}
没问题。输出:
INSERT INTO myTable VALUES ('0000000','D00','20200901131010','20200917133115','20200917142400','20200923120401','N');
我的问题是我需要使用下面的函数转换$ 3,$ 4和$ 5字段。但我认为awk不允许调用其他函数,例如
createInsert(){
echo $1 | awk -F'@' '{
printf "INSERT INTO myTable VALUES (\x27%s\x27,\x27%s\x27,\x27%s\x27,\x27%s\x27,\x27%s\x27,\x27%s\x27,\x27%s\x27);",$1,$2,**$(funcion $3)**,$4,$5,$6,$7;print ""
}'
}
是否可以创建任何形式?一个单独的方法将字段$ 3、4和5拆分为与其他函数相同的方法(将其创建为toDate函数)
谢谢,希望你的回答。
摘要:输入:
`"0000000@D01@000000@20200910103010@20200910111111@20200910100403@N@"`
输出:
INSERT INTO myTable VALUES ('0000000','D01','000000','to_date('2020/09/10:10:30:10', 'yyyy/mm/dd:hh24:mi:ss')',''to_date('2020/09/11:11:11:11', 'yyyy/mm/dd:hh24:mi:ss')','to_date('2020/10/10:04:03', 'yyyy/mm/dd:hh24:mi:ss')','N');
你能否尝试以下内容,这完全基于GNU中显示的OP示例awk
。如果你的字段编号与显示的示例不同,请尝试更改解决方案中的字段编号,它应该对你有用。我还认为,7243176
如果不是这样,你需要对显示的值进行硬编码,然后可以将相应的字段编号放在此处它。
awk -v s1="'" '
BEGIN{
FS="@"
OFS="\047, \047"
}
{
print "INSERT INTO myTable VALUES(\0477243176",$2,$1,\
"to_date(\047" substr($4,1,4)"/"substr($4,5,2)"/"\
substr($4,7,2)":"substr($4,9,2)":"substr($4,11,2)":"\
substr($4,13,2),"yyyy/mm/dd:hh24:mi:ss\047)","\
to_date(\047" substr($5,1,4)"/"substr($5,5,2)"/"\
substr($5,7,2)":"substr($5,9,2)":"substr($5,11,2)\
":"substr($5,13,2),"yyyy/mm/dd:hh24:mi:ss\047)\
" ",\047N\047)"
}
' Input_file
同样考虑到这"
不是你的示例输入的一部分,如果可以的话,你可以使用sub
函数将其替换为awk
程序的主块。