且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-02-22 13:18:15

我建议使用适当的Awk脚本,如下所示.这样可以满足您在问题中所述的要求,并创建两个文件ABC_COMPANY.txtABC_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