首页 > 解决方案 > 如何对未知(但重复)的单词进行分组以创建索引?

问题描述

我必须创建一个 shellscript,通过获取封装在尖括号 (<>) 中的任何单词并从中制作索引文件来索引一本书(文本文件)。我有两个问题希望你能帮助我!

首先是如何识别文本中包含在尖括号内的单词。我发现了一个类似的问题,但需要在方括号内输入单词,并试图操纵他们的代码,但出现错误。

grep -on \\<.*> index.txt

原始代码是相同的,但使用方括号而不是尖括号,现在我收到一条错误消息:

line 5: .*: ambiguous redirect

这个已经回答了

我现在还需要从以下位置获取索引并重新格式化它:

1:big
3:big
9:big
2:but
4:sun
6:sun
7:sun
8:sun

进入:

big: 1 3 9
but: 2
sun: 4 6 7 8

我知道我可以使用 awk 命令翻转列,例如:

awk -F':' 'BEGIN{OFS=":";} {print $2,$1;}' index.txt

但我不确定如何将相同的单词组合成一行。

谢谢!

标签: regexbashawk

解决方案


您能否尝试以下操作(如果您不担心排序顺序,以防您需要对其进行排序,然后附加sort到以下代码)。

awk '
BEGIN{
  FS=":"
}
{
  name[$2]=($2 in name?name[$2] OFS:"")$1
}
END{
  for(key in name){
    print key": "name[key]
  }
}
' Input_file

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

awk '                                        ##Starting awk program from here.
BEGIN{                                       ##Starting BEGIN section from here.
  FS=":"                                     ##Setting field separator as : here.
}
{
  name[$2]=($2 in name?name[$2] OFS:"")$1      ##Creating array named name with index of $2 and value of $1 which is keep appending to its same index value.
}
END{                                         ##Starting END block of this code here.
  for(key in name){                          ##Traversing through name array here.
    print key": "name[key]                   ##Printing key colon and array name value with index key
  }
}
' Input_file                                 ##Mentioning Input_file name here.

推荐阅读