【问题标题】:Indexing words in a file according to their line with AWK [closed]根据 AWK 的行索引文件中的单词 [关闭]
【发布时间】:2021-03-21 23:48:57
【问题描述】:

假设我有一个类似于以下的文件:

hello
hello
hi
hi
hello
hey

我想查找每个唯一行的索引并使用逗号作为索引分隔符。所以理想情况下,输出应该是:

hello 1,2,5
hi 3,4
hey 6

使用以下代码获取行的值做了什么,

{ arr[$0]++ }
END { for (i in arr) {
        print i
    }
}

结果是,

hey
hi
hello

【问题讨论】:

  • edit您的问题展示您迄今为止所做的尝试,以便我们为您提供帮助。见How to Ask
  • 请注意,文件中唯一唯一的行是“嘿”。
  • 如果您想快速了解这些,我会使用:cat -n <file>

标签: awk indices


【解决方案1】:

试试这个脚本

{
  words[$0] = words[$0] == "" ? FNR : words[$0] "," FNR        # appends the line, sorting for the word
}

END {                                # once we are done reading the file
  for (w in words)                     # for each word, the sorting order depends on awk internal variables.
  {
    print w, words[w]             # prints the desired output
  }
}

请参阅Controlling Array Traversal 了解有关如何打印单词以及如何控制它的更多详细信息。有关 FNR 的更多详细信息,请参阅What are NR and FNR

【讨论】:

  • 我已经尝试过这个脚本,但是存在一些问题。首先,for 语句中需要括号。其次,修复后,结果看起来像hey 2,其中所有三行的第二列都是2。
  • 啊,是的,你是对的。让我为你解决这个问题。另外,我借此机会使用了一个更优雅的解决方案来管理第一行的逗号。尽管如此,它仍然是众多可能性之一。您的实施并不太远,但您没有跟踪行号,只跟踪记录内容。
猜你喜欢
  • 1970-01-01
  • 2011-10-21
  • 2011-11-14
  • 2017-04-04
  • 1970-01-01
  • 2020-12-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-30
相关资源
最近更新 更多