【问题标题】:How to open a file and create new file from the content of first file如何打开文件并从第一个文件的内容创建新文件
【发布时间】:2020-05-26 09:20:12
【问题描述】:

我有一个输入文件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;

【问题讨论】:

  • 请分享您到目前为止尝试过的内容。
  • 我在这里也是第二个 Digvijay,因此我们鼓励用户添加他们为解决自己的问题所做的努力,所以请添加相同的内容并让我们知道。顺便说一句,一旦您添加努力,我的答案就准备好了,我会发布我的答案:)
  • 是的,同意....我已经用 perl 脚本编写了代码,因为我在 shell 中找不到太多寻求帮助。在此处添加 perl 编码。
  • @teepu,当然你可以在你的问题中添加该代码,这不是问题,没有错,或者大家都在这里学习,干杯。
  • 请参阅stackoverflow.com/help/formatting,了解如何正确格式化您的示例输入、输出和代码以在此站点上发布。

标签: shell unix awk


【解决方案1】:

请您尝试关注一下。

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

【讨论】:

  • 我怀疑close 调用是不必要的。我不确定,但如果达到文件限制,任何体面的 awk 实现似乎都应该透明地处理它,所以这可以大大简化为awk '{print &gt; substr($0,1,2)}' input。如果一个实现不能干净地处理那个......坚持使用 perl。
  • @WilliamPursell 仅 GNU awk 处理的打开文件数量超过了限制,因此如果您要创建十几个左右的输出文件,则需要随时关闭()它们以实现可移植性。恕我直言,这不是使用 perl 的理由。
  • &gt;set name="test" &gt;awk -v shell_var="${name}" ' { output_file=shell_var substr($0,1,2)".txt" } { print &gt;&gt; (output_file);close(output_file) } ' file awk: syntax error near line 1 awk: bailing out near line 1
  • @teepu 好的,现在您给出了完全错误您使用的是 sun Solaris o.s 吗?如果是,则将 awk 更改为 nawk 然后运行代码,让我知道
  • 问题已通过nawk/usr/xpg4/bin/awk 解决:)
【解决方案2】:

使用 GNU awk 处理多个同时打开的文件:

awk '{print > (substr($0,1,2) ".txt")}' file

使用任何 awk +sort 以提高效率,只需关闭/打开每个输出文件,因为所有具有相同前 2 个字符的字符串的输出文件名都会发生变化,而不必对每一行都这样做:

awk '{print NR, substr($0,1,2), "," $0}' file |
sort -k2,2 -k1,1n |
awk '$2 != prev{close(out); out=$2 ".txt"; prev=$2} {sub(/[^,]+,/,""); print > out}'

【讨论】:

    猜你喜欢
    • 2015-05-03
    • 2013-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-01
    • 1970-01-01
    • 2013-03-07
    相关资源
    最近更新 更多