根据某些条件将一个文件拆分为多个文件

时间:2013-02-27 17:53:50

标签: bash unix

我有一个包含1个月数据的文件,我和2月份 需要每天拆分文件,即将Feb文件拆分为Feb_1Feb_2 ... Feb_29

这是我的逻辑:

Inputfile= $1
monthname = "Feb"
while getopts :
datefield="1"
outfile="Feb_1"

while read line    
do
s = `echo "$line" | awk '{print $2}'`
t = `echo "$line" | awk '{print $3}'`
if [ "$s" = "$monthname" ]
    if [ "$t" = "$datefield" ] 
         echo $line > "$outfile"
    else
         datefield = $t
         outfile =$monthaname"_"$t
         echo $line > "$outfile"
    fi
else
  echo $line > "$outfile"
fi 
done < "$inputfile"

但是s = echo "$line" | awk '{print $2}'

这不是第二个字,因为我正在使用$2请求第二个命令行参数。我尝试将'放在$2之前,如下所示。

s = echo "$line" | awk '{print '$2}'

在这种情况下,它会抛出一个新错误,假设第一行是Wed Feb 1它的抛出错误Wed Feb 1不存在。

以下是示例数据:

Wed Feb 1 00:10:00 cpu usage    
KLOGENT.exe 3068 SYSTEM 00 0:00:00 17345K 15467 BELOW NORMAL    
SGHT.exe 3868 SYSTEM 00 0:00:00 18845K 15499 BELOW NORMAL    
.......    
.......    
Wed Feb 1 00:15:00 cpu usage    
KLTREENT.exe 3068 SYSTEM 00 0:00:00 17345K 15767 BELOW NORMAL    
KJTRT.exe 3868 SYSTEM 00 0:00:00 18845K 13699 BELOW NORMAL    
..............   
...........    
Wed Feb 1 23:55:00 cpu usage    
HTR.exe 3068 SYSTEM 00 0:00:00 1785K 4532 BELOW NORMAL    
KLU.exe 3868 SYSTEM 00 0:00:00 15645K 678 BELOW NORMAL    
...............   
.................   
Thu Feb 2 00:10:00 cpu usage
JUYT.exe 3068 SYSTEM 00 0:00:00 143245K 157767 BELOW NORMAL   
GFD.exe 3868 SYSTEM 00 0:00:00 18845K 879 BELOW NORMAL    
.........................    
.......................    
Thu Feb 28 00:15:00 cpu usage    
FRE.exe 3068 SYSTEM 00 0:00:00 143245K 157767 BELOW NORMAL    
YUT.exe 3868 SYSTEM 00 0:00:00 18845K 879 BELOW NORMAL    
............................    
...................    
Thu Feb 28 23:55:00 cpu usage    
TRE.exe 3068 SYSTEM 00 0:00:00 143245K 157767 BELOW NORMAL    
KJH.exe 3868 SYSTEM 00 0:00:00 18845K 879 BELOW NORMAL

2 个答案:

答案 0 :(得分:2)

凝视我的水晶球以确定输入数据,您需要:

awk '{print > $2 "_" $3 }' input-file

或可能

awk '$2 == "Feb" {print > $2 "_" $3 }' input-file

如果输入的实际格式已知,那么提供解决方案会简单得多。

答案 1 :(得分:1)

awk '/Feb/{file=$2"_"$3}{print $0>file".txt"}' your_log