【发布时间】:2020-09-22 04:42:02
【问题描述】:
我有一个文件file1.dml 和另一个固定长度的数据文件file2.dat。 file1.dml 中的数据是这样的
start
integer(16) field1 ;
string(1) filed2 ;
string(80) filed3 ;
decimal(16.2) field4;
string(1) newline = "\n";
end;
file2.dat 中的数据类似于
12345678 ABBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB 1234567890
我需要如下的输出文件
field1="12345678 "
filed2="A"
filed3="BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB "
field4="1234567890 "
newline="\n"
我已经编写了下面的函数,它接受 file1.dml 和 file2.dat 并生成确切的结果,但我想使用 AWK 简化它,提前感谢任何帮助
function myfunc1
{
if [ $1 == "" -a $2 == "" -a ! -f $1 -a ! -f $2 ]; then
print "Input files not present"
else
dml_file=$1 #input parameter, dml file
cntl_file=$2 #input parametr, dat file
start_pos=1
end_pos=0
cat "$dml_file" | sed '1d' | sed '$d' | while IFS= read line
do
counter=`echo $line | cut -d'(' -f2 | cut -d')' -f1`
fld_name=`echo $line | cut -d'(' -f2 | cut -d')' -f2 | sed 's/;//g'`
#check decimal or not
if [[ $counter == +([0-9]) ]]; then
end_pos=$((counter+start_pos))
else
counter1=`echo $counter | cut -d'.' -f1`
counter=$counter1
end_pos=$((counter1+end_pos))
fi
newline_check=`echo $fld_name | grep -i 'newline' | wc -l`
if [ $newline_check -gt 0 ]; then
fld_name="newline"
fld_val="\n"
#write below line in one file
echo "$fld_name : \"$fld_val\""
else
fld_val=`cat $cntl_file | cut -c$start_pos-$end_pos`
#write below line in one file
echo "$fld_name : \"$fld_val\""
fi
start_pos=$((start_pos+counter))
done
fi
}
【问题讨论】:
-
到目前为止您尝试过什么:使用
awk?file2.dat是否总是被限制为一行file1.dat是否有多个start/end块,如果是这样,输出应该是什么样子?我读对了吗...您想忽略field4的scale/.2部分吗? -
使用 AWK 我能够获取字段名称和长度,到目前为止没有别的。 file2.dat 将始终是单行。总会有一个从第一行开始,到最后一行结束。 scale 16.2 表示,数据长度只有 16,scale 2 可以忽略。