regex - 如何对未知(但重复)的单词进行分组以创建索引?
问题描述
我必须创建一个 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
但我不确定如何将相同的单词组合成一行。
谢谢!
解决方案
您能否尝试以下操作(如果您不担心排序顺序,以防您需要对其进行排序,然后附加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.
推荐阅读
- python - 将轮子上传到 github 版本时出现资产路径错误
- vue.js - 为什么这个 $emit 事件在 Vue.js 中的组件和父级之间不起作用?
- c# - 未在二叉搜索树 C# 中添加节点
- php - 使用 PHP 接收 Blob 并存储到 mySQL 数据库
- html - 菜单 ul 元素未显示在 h1 和图标下方
- python - 如果 ```.pyc``` 文件只包含导入模块的字节码,主文件 (.py) 中的其他代码如何执行?
- r - 在网络上部署闪亮的应用程序而不使用任何服务器(如闪亮的服务器,shinnyapps.io)
- django - Django:为什么 POST 到 UpdateView 静默失败?
- sql - 获取表中第一个可用索引,包括0
- javascript - Axios 发布大文件