使用unix从一个文件创建两个文件

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

我有一个输入文件,我需要读取并应用一些条件和路由到另外两个文件。

100 COMPANY Records
500ABC COMPANY 345         
2pen9999out
2cow7777out
2goa7777out
500ABC COMPANY IN 456
2car9999out
2cow7777out
2HAT7777out
2BAL9999out
2BAL6666out

这里,记录以5开头是标题,2是详细信息

我需要创建两个文件ABC_COMPANY.txtABC_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
shell unix awk sed sh
1个回答
2
投票

我建议使用适当的Awk脚本,如下所示。这需要按照问题中的说明实现您的要求,并创建两个文件ABC_COMPANY.txtABC_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
© www.soinside.com 2019 - 2024. All rights reserved.