如何从unix的ONE文件中逐行读取并拆分为两个文件

时间:2017-12-21 07:22:20

标签: shell unix awk sed sh

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

我的输入文件company.txt

100ABC COMPANY          
2pen9999out
2cow7777out
2goa7777out
100XYZ COMPANY 
2car9999out
2cow7777out
2HAT7777out
2BAL9999out

这里,记录开头是1是标题,2是详细

我需要创建两个文件100ABC.txt和100XYZ.txt?

首先我需要检查

inline = = $(cut -f 0-1 $ line)   compnayName = = $(cut -f 4-6 $ line)

if [ $inline -eq "1"` ] and $compnayName="ABC"
 if(record start with 2 and  position 4 to 8 has value like 7777)
    if yes,  route them in 100ABC.txt

输出:100ABC.txt

2cow7777out
2goa7777out

同样我需要检查下一家公司XYZ,

如果[$ inline -eq" 1"`]和$ compnayName =" XYZ"     if(记录以2开头,位置4到8的值如7777)         如果是,请在100XYZ.txt

中路由它们

喜欢XYZ.txt

 2cow7777out
 2HAT7777out

1 个答案:

答案 0 :(得分:2)

尝试:

$ awk '/^1/{close(f); f=$1 ".txt"} /^2...7777/{print>f}' company.txt

运行此命令后,目录中将有两个新文件:

$ ls
100ABC.txt  100XYZ.txt  company.txt

文件将包含内容:

$ cat 100ABC.txt 
2cow7777out
2goa7777out

$ cat 100XYZ.txt 
2cow7777out
2HAT7777out

如何运作

  1. /^1/{close(f); f=$1 ".txt"}

    如果当前行以1开头,则关闭文件f(如果存在)并为f分配一个新值,该值由第一个字段后跟{{1}组成}}

  2. .txt

    如果当前行以/^2...7777/{print>f}开头,其中2...777匹配任何字符,则将此当前行打印到文件.