【问题标题】:"for each file"-loop inside awk script“对于每个文件”-在 awk 脚本中循环
【发布时间】:2012-09-01 01:00:03
【问题描述】:

我现在写了一个 AWK 函数,应该是这样的:

  function inser_styles(path_to_files, output_file) {
    for each input_file in path_to_files {
      print "" > output_file;
      while ( getline < input_file ) {
        print "   " $0 > output_file;
      }
    }
    print "" > output_file;
  }

它应该从一些path_to_files目录中读取文件并将每个input_file的所有内容放入一些output_file中,用空行分隔。

for each input_file in path_to_files {...} - 循环是什么样子的? awk 是否支持这种 for 循环,或者我应该使用 ls 的 extern execute 读取文件名数组?

【问题讨论】:

  • 该函数是一个 AWK 函数(不是 shell),所以它是在 AWK 脚本中定义的。
  • AWK 没有自己的通配符或目录遍历功能。
  • 似乎是这样。您可能知道任何证明链接吗? (我什么都没找到)

标签: unix for-loop foreach awk


【解决方案1】:

您可以使用find 实用程序来获取文件名。请注意,如果文件名包含换行符,这将无法正常工作。指定您希望与find 一起使用的任何其他选项。

function insert_styles(path_to_files, output_file) {
    cmd = "find " path_to_files " -maxdepth 1 -type f"
    while (cmd | getline input_file > 0) {
        print "" > output_file;
        while ( getline < input_file ) {
            print "   " $0 > output_file;
        }
        close(input_file)
    }
    close(cmd)
    print "" > output_file;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-06-16
    • 2019-11-30
    • 2013-11-22
    • 2020-05-11
    • 1970-01-01
    • 1970-01-01
    • 2012-03-22
    • 2020-04-06
    相关资源
    最近更新 更多