【问题标题】:Unable to separate codes in one file to many files in AWK/Python无法将一个文件中的代码分离到 AWK/Python 中的多个文件
【发布时间】:2010-10-12 14:08:14
【问题描述】:

我需要将不同的代码放在一个文件中的多个文件中。 该文件显然由 AWK 的创建者在其主页上共享。 该文件也是here,方便使用。

我对这个问题的尝试

我可以得到每个代码所在的行

awk '{ print $1 }'

但是,我不知道怎么做

  1. 获取确切的行号以便我可以使用它们
  2. 收集特定行之间的代码,以便忽略每行的第一个单词
  3. 将这些单独的代码放入以该行的第一个单词命名的新文件中

我确信这个问题可以通过 AWK 和 Python 来解决。也许,我们需要一起使用它们。

[编辑]在第一个答案之后

当我尝试使用 awk 执行时出现以下错误

$awk awkcode.txt 
awk: syntax error at source line 1
 context is
     >>> awkcode <<< .txt
awk: bailing out at source line 1

【问题讨论】:

    标签: python awk


    【解决方案1】:

    您是否要解压缩该格式的文件?它是一种 shell 存档。欲了解更多信息,请参阅http://en.wikipedia.org/wiki/Shar

    如果您使用 awk 执行该程序,则 awk 将创建所有这些文件。您不需要编写或重写太多。你可以简单地运行那个 awk 程序,它应该仍然可以工作。

    首先,以“普通”格式查看文件。 http://dpaste.com/12282/plain/

    其次,将文件的普通版本保存为'awkcode.shar'

    第三,我认为你需要使用以下命令。

    awk -f awkcode.shar
    

    如果你想用 Python 程序替换它,它会是这样的。

    import urllib2, sys
    
    data= urllib2.urlopen( "http://dpaste.com/12282/plain/" )
    currName, currFile = None, sys.stdout
    for line in data:
        fileName, _, text= line.strip().partition(' ')
        if fileName == currName:
            currFile.write(line+"\n")
        else:
            if currFile is not None:
                currFile.close()
            currName= fileName
            currFile= open( currName, "w" )
    if currFile is not None:
        currFile.close()
    

    【讨论】:

    • 删除前 3 行后出现以下错误 $awk -f awkcode.shar awk: syntax error at source line 1 source file awkcode.shar context is >>> emp
    • Python 代码出现以下错误:NameError: name 'sys' is not defined WARNING: Failure execution file:
    • 已修复。 "fileName, _, text= line.strip().partition(' ')" 你应该学Python,你可以自己调试。
    【解决方案2】:

    您是否尝试过:

    1. 创建具有以下内容的文件 unbundle.awk:

    $1 != prev { close(prev);上一页 = $1 } { print substr($0, index($0, " ") + 1) >$1 }

    1. 从文件 awkcode.txt 中删除以下行:

      # unbundle - 将捆绑包解压到单独的文件中

    $1 != prev { close(prev);上一页 = $1 } { print substr($0, index($0, " ") + 1) >$1 }

    1. 运行以下命令:

    awk -f unbundle.awk awkcode.txt

    【讨论】:

    • 我收到以下错误:$awk -f unbundle.awk awkcode.txt awk: can't open file unbundle.awk source line number 1 source file unbundle.awk context is >>>
    • 您是否先创建了文件 unbundle.awk?可以访问吗?
    • 谢谢!我不知道文件中的第一条语句是 AWK 命令 :)
    【解决方案3】:

    Awk 文件 awkcode.txt 不应包含任何空白行。如果遇到任何空行,则 awk 程序将失败。没有错误检查来过滤掉代码中的空白行。经过几天的奋斗,我可以发现这一点。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-12-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-24
      相关资源
      最近更新 更多