我有一个输入文件,我需要读取并应用一些条件并路由到另外两个文件。
100 COMPANY Records
500ABC COMPANY 345
2pen9999out
2cow7777out
2goa7777out
500ABC COMPANY IN 456
2car9999out
2cow7777out
2HAT7777out
2BAL9999out
2BAL6666out
这里,记录从5开始是标题,2是详细信息
我需要创建两个文件ABC_COMPANY.txt
和ABC_COMPANY_IN.txt
?
我写了下面的逻辑,我想用awk
或其他正确的方法转换?
NUMBER1="666"
NUMBER2="777"
while read line
do
REC_IND=`echo "${line}" | awk '{print substr($1,1,1)}'`
if [ "${REC_IND}" = "5" ]; then
FILENAME="ABC_COMPANY"
DEAIL_COMPANY=`echo "${line}" | awk '{print substr($0,3,7)}'`
if [[ $DEAIL_COMPANY = "ABC COMPANY IN" ]]; then
FILENAME="ABC_COMPANY_IN"
fi
fi
#check for detail record
if [ "${REC_IND}" = "2" ] ;then
#substring to find value
Value=`echo "${line}" | awk '{print substr($0,4,9)}'`
#if record belongs to bank then route to the respective file
if [ "$Value" = "$NUMBER1" ] || [ "$Value" = "$NUMBER2" ] ; then
echo $line >> ${FILENAME}".txt"
fi
fi
done < /bk/shan.txthere
预期产出:
ABC_COMPANY.txt
2cow7777out
2goa7777out
ABC_COMPANY_IN.txt
2cow7777out
2HAT7777out
2BAL6666out
答案 0 :(得分:2)
我建议使用正确的Awk
脚本,如下所示。这会照照问题中的说明实现您的要求,并创建两个文件ABC_COMPANY.txt
和ABC_COMPANY_IN.txt
,其中包含问题中提到的内容。
#!/usr/bin/env awk
$1 ~ /^5/ {
gsub(/[0-9]+/,"")
gsub(/^[[:space:]]+|[[:space:]]+$/,"")
gsub(/[[:space:]]/,"_")
header=$0".txt"
openhandles[len++] = header
}
$1 ~ /^2/ && $1 ~ /666|777/ {
print > header
}
END {
for (i=0; i<len; i++ )
close(openhandles[i])
}
以
运行脚本awk -f script.awk inputfile
您可以使用脚本的命令行版本
awk '$1 ~ /^5/ { gsub(/[0-9]+/,""); gsub(/^[[:space:]]+|[[:space:]]+$/,"");
gsub(/[[:space:]]/,"_"); header=$0".txt"; openhandles[len++] = header; }
$1 ~ /^2/ && $1 ~ /666|777/ { print > header }
END {for (i=0; i<len; i++ ) close(openhandles[i]) }' file