简体   繁体   English

如何打印BASH中搜索到的字符后出现的n个字符?

[英]How to print n number of characters appearing after a searched character in BASH?

I have a text file like this: 我有一个这样的文本文件:

Once upon a time, there lived a rabbit who lived in the forest.
One day, rabbit found bear.
Bear said, "Hello!"

Given a letter, eg "e", I need to output all searches for e + the next 2 characters , eg, this will print the following: 给定字母,例如“ e”,我需要输出所有e + the next 2 characters ,例如,这将输出以下内容:

e u
e, 
ere
e l
ed 
ed 
est
e d
ear
ear
ell
  • Any character, including punctuation or symbols can be printed, but not a newline. 可以打印任何字符,包括标点符号或符号,但不能打印换行符。
  • This is case sensitive. 这是区分大小写的。 If "e" is searched, it does not look for "E". 如果搜索“ e”,则不会查找“ E”。

How can I print a searched for character plus the next 2 characters each time the searched character appears in a file in BASH? 每当搜索到的字符出现在BASH文件中时,如何打印搜索到的字符以及接下来的2个字符?

Can you use perl ? 可以使用perl吗?

perl -lne 'print "e",$_ for $_ =~ /(?<=e)(..)/g' file

$ perl -lne 'print "e",$_ for $_ =~ /(?<=e)(..)/g' file
e u
e, 
ere
e l
ed 
ed 
e f
est
e d
ear
ear
ell

To include overlapping strings, you can use this: 要包含重叠的字符串,可以使用以下命令:

while IFS= read -r line
do
    while [ "${#line}" -gt 2 ]
    do
        if [ "${line:0:1}" = 'e' ]
        then
            echo "${line:0:3}"
        fi
        line="${line:1}"
    done
done

如果您的grep支持-o,那么很简单

grep -o e..

The hard way 艰难的道路

echo $(cat file.txt ) > temp
grep -o . temp | nl | grep e | cut -f1 | xargs -i -n1 echo "{}; {} + 2;" | bc | xargs -n2 echo | sed 's/ /-/' |  xargs -i{} -n 1 cut -c {} temp

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM