【发布时间】:2014-10-13 22:27:23
【问题描述】:
在执行此操作时遇到一些问题。输出需要采用以下格式:在每一行上,首先打印一个单词,然后是一个冒号“:”,然后是一个空格,然后是该单词出现的行号列表(以逗号分隔)。如果一个词在一行中出现多次,它应该只报告该行的一次。
命令行:index.awk test1.txt > new.output.txt
我的代码(当前):
#!/bin/awk -f
Begin {lineCount=1} # start line count at 1
{
for (i = 1; i <= NF; i++) # loop through starting with postition 1
for ( j = 2; j <= NF; j++) # have something to compare
if ( $i == $j ) # see if they match
print $i ":" lineCount # if they do print the word and line number
lineCount++ # increment the line number
}
您会在下面的示例输出中注意到它完全跳过了输入文本文件的第一行。它从那里正确计数。如果单词出现不止一次,我如何打印它?另外,awk 是否有一个本机函数可以解释错误字符,例如标点符号、数字、[]、() 等...
(EDIT: gsub(regexp, replacement, target) 可以从文本中省略这些错误字符。
示例输入:我想打印出每个单词,并且 单词出现的对应行。我需要确定 我在打印出来时省略了字符串中的标点符号。作为 好吧,我需要确定这个词是否在一行中出现了不止一次 不要将行号打印两次。
SAMPLE OUTPUT:
I:
would:
like:
to:
print:
out:
each:
word:
and,:
the:1
corresponding:
lines:
which:
the:
word:
occurs:
on.:
I:1
need:1
to:1
make:1
sure:1
.....ect (outputs the line numbers correctly from here)
【问题讨论】:
-
一些示例输入也很有用。
-
感谢您的建议,刚刚添加了一些示例输入。
-
有什么建议吗? @TomFenech
-
为什么
and,和on.被认为是“单词”?定义一个“词”对你意味着什么。 -
@Ryan 识别单词是大局,其余的都是微不足道的。更新您的问题以显示您认为难以处理的一些输入案例(例如,
There、there和there's是同一个词吗?尾随的s是一个词吗?7是一个词吗?7th?)和你真正想要的输出呢。
标签: shell awk scripting gawk scripting-language