首页 > 解决方案 > 如何打开文件并从第一个文件的内容创建新文件

问题描述

original.txt我有一个内容为的输入文件

AS1023000404 SA26376 EFadadhkaj ASssjdiw9128129010210 EF939809

在这里,我想根据First 2 letters of each line给定的原始文件创建新文件,我应该有以下内容。

file 1 = AS.txt content: AS1023000404 ASssjdiw9128129010210

File 2 = SA.txt Content: SA26376

File 3 = EF.txt Content: EFadadhkaj EF939809

任何人都可以帮助我如何实现这一目标。

在此处添加我尝试过的 perl 代码。

while (<$INFILE>) { if (length($_) > 0) { $outFlName = substr($_,$start,$len);

` if (not $OUTFILE{$outFlName}) {
     open $OUTFILE{$outFlName}, '>', "${outFlName}.txt"
       or die "Unable to open '${outFlName}.txt' for output: $!";
     $OUTREC{$outFlName} = 0;
 }
 print { $OUTFILE{$outFlName} } $_;
 $OUTREC{$outFlName} = $OUTREC{$outFlName} + 1;`

} } close $_ for values %OUTFILE;

标签: shellunixawk

解决方案


请您尝试以下操作。

awk '
{
  output_file=substr($0,1,2)".txt"
}
{
  print >> (output_file)
  close(output_file)
}
' Input_file

说明:为上述添加详细说明。

awk '                                   ##Starting awk program from here.
{
  output_file=substr($0,1,2)".txt"      ##Creating output_file which has first 2 letters of current line.
}
{
  print >> (output_file)                ##Printing line to output file.
  close(output_file)                    ##Closing output file in back ground.
}
' file

推荐阅读