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 u
e,
ere
e l
ed
ed
est
e d
ear
ear
ell
How can I print a searched for character plus the next 2 characters each time the searched character appears in a file in BASH?
Can you use 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.