圈出单词并提取双字母组

问题描述 投票:0回答:3

我想从给定的单词中提取每个二元组,并放入一个文本文件中。

例如:

apple      -->       ap pp pl le
president  -->       pr re es si id de en nt

我发现使用awk和word进行类似的工作,但关于单词一无所获。

我刚刚找到此代码:

sed 's/\(.\{2\}\)/\1 /g' 

但它的窗口大小为2。

因此,例如:

apple      -->      ap pl le

感谢您的帮助

sed 's/\(.\{2\}\)/\1 /g' 

预期的结果是一个窗口大小为1的字符串bigram。

unix awk sed text-processing
3个回答
1
投票

我会这样:

$ sed 's/./&&/g;s/^.//;s/.$//;s/../& /g;s/ $//' <<< $'president\napple'
pr re es si id de en nt
ap pp pl le

sed命令在这里拆分:

s/./&&/g      # Duplicate every character:   "pprreessiiddeenntt"
s/^.//        # Remove first character:      "prreessiiddeenntt"
s/.$//        # Remove last character:       "prreessiiddeennt"
s/../& /g     # Insert blank between groups: "pr re es si id de en nt "
s/ $//        # Remove trailing blank:       "pr re es si id de en nt"

1
投票

awk可以很简单地做到这一点:

$ cat file.txt
 apple
 president
 example
 another

$ awk '{output=""; for(i=1;i<length($0);i++){ output=output" "substr($0,i,2)} print output }' file.txt
 ap pp pl le
 pr re es si id de en nt
 ex xa am mp pl le
 an no ot th he er

如果行前的空格有问题,您可以通过多种方式处理它,例如在子字符串之前添加空格之前检查输出是否为空,或者仅在空格之后提取输出的子字符串,例如]]

$ awk '{output="";for(i=1;i<length($0);i++){ output=output" "substr($0,i,2)} print substr(output,2) }' file.txt
ap pp pl le
pr re es si id de en nt
ex xa am mp pl le
an no ot th he er

{ }块内的所有内容均针对每行执行,因为它没有附加条件。

[output=""将每行的输出变量重置为空。

[for(i=1;i<length($0);i++){ ... }逐字符循环遍历字符串。

output=output" "substr($0,i,2)} print output-这在上述循环内执行。对于字符串的每个字符,输出变量将分配给它的现有值,一个空格,然后是当前索引中的两个字符子字符串-遍历每个字符并打印它和下一个字符。


0
投票

在GNU awk上,您可以:

© www.soinside.com 2019 - 2024. All rights reserved.