问题描述
我已经四处搜寻,但仍然找不到这个简单的答案.我敢肯定这很容易.如果您知道如何完成此操作,请提供帮助.
I've searched all over and still cant find this simple answer. I'm sure its so easy. Please help if you know how to accomplish this.
sample.txt是:
sample.txt is:
AAAAA
我想找到组合"AAA"发生的确切时间.如果仅以
I want to find the exact times the combination "AAA" happens. If you just use for example
grep -o 'AAA' sample.txt | wc -l
我们收到一个1.这与使用标准文本编辑器搜索框类型搜索来搜索AAA发生的次数相同.但是,我想要完全匹配的完整数目,从每个字符正好是3开始.当我们分别从每个字符中搜索而不是将每个AAA命中都当作盒子类型块时,就会得到此匹配.
We receive a 1. This is the same as just searching the number of times AAA happens from with a standard text editor search box type search. However, I want the complete number of matches exactly, starting from each individual character which is exactly 3. We get this when we search from each character individually instead of treating each AAA hit like a box type block.
我要寻找的是从sample.txt中每个"AAA"字符开始的,被压缩最多/可能性最大的/确切的字数,而不是每次在正常文本中都找到它时所遇到的障碍在搜索框中搜索编辑器类型.
I am looking for the most squeezed in/most possibilities/literal exact number of occurences starting from every individual character of "AAA" in sample.txt, not just blocks of every time it finds it like it does in a normal text editor type search from the search box.
我们如何做到这一点(最好是在AWK中)? SED,GREP和其他任何东西都可以,而且我可以将其包含在Bash脚本中.
How do we accomplish this, preferrably in AWK? SED, GREP and anything else is fine as well as I can include in a Bash script.
推荐答案
在bash中这不是一个小问题.据我所知,标准工具不支持这种搜索.但是,您可以使用标准bash功能在函数中实现此行为.这是解决问题的方法,但是还有其他方法:
This isn't a trivial problem in bash. As far as I know, standard utils don't support this kind of searching. You can however use standard bash features to implement this behavior in a function. Here's how I would attack the problem, but there are other ways:
#!/bin/bash
search_term="AAA"
text=$(cat sample.txt)
term_len=${#search_term}
occurences=0
# While the text is greater than or equal to the search term length
while [ "${#text}" -ge "$term_len" ]; do
# Look at just the length of the search term
text_substr=${text:0:${term_len}}
# If we see the search term, increment occurences
if [ "$text_substr" = "$search_term" ]; then
((occurences++))
fi
# Remove the first character from the main text
# (e.g. "AAAAA" becomes "AAAA")
text=${text:1}
done
printf "%d occurences of %s\n" "$occurences" "$search_term"
这篇关于BASH:搜索字符串并确切显示子字符串在其中发生的确切次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!