使用Unix从一个文件创建两个文件 [英] Creating two files from one file using unix
问题描述
我有一个输入文件,我需要阅读并应用一些条件,然后路由到另外两个文件.
I have one input file, I need to read and apply some condition and route to two other files.
100 COMPANY Records
500ABC COMPANY 345
2pen9999out
2cow7777out
2goa7777out
500ABC COMPANY IN 456
2car9999out
2cow7777out
2HAT7777out
2BAL9999out
2BAL6666out
在这里,记录从5开始是标题,而2是详细信息
here, record start with 5 was header and 2 was detail
我需要创建两个文件ABC_COMPANY.txt
和ABC_COMPANY_IN.txt
吗?
i need to create two file ABC_COMPANY.txt
and ABC_COMPANY_IN.txt
?
我在下面编写了逻辑,我想使用awk
或其他正确方法进行转换?
I have written below logic, which I want to convert using awk
or other right approach?
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
推荐答案
我建议使用适当的Awk
脚本,如下所示.这样可以满足您在问题中所述的要求,并创建两个文件ABC_COMPANY.txt
和ABC_COMPANY_IN.txt
,其中包含问题中提到的内容.
I would recommend using a proper Awk
script like something below. This takes care of achieving your requirement as stated in the question and creates two files ABC_COMPANY.txt
and ABC_COMPANY_IN.txt
with contents as mentioned in the question.
#!/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
您可以将脚本的命令行版本用作
You can use the command-line version of the script as
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
这篇关于使用Unix从一个文件创建两个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!