Wednesday, December 29, 2021

[SOLVED] extract the adjacent character of selected letter

Issue

I have this text file:

# cat letter.txt
this
is
just
a
test
to
check
if
grep
works

The letter "e" appear in 3 words.

# grep e letter.txt
test
check
grep

Is there any way to return the letter printed on left of the selected character?

expected.txt
t
h
r

Solution

You can use positive lookahead to match a character that is followed by an e, without making the e part of the match.

cat letter.txt | grep -oP '.(?=e)'


Answered By - Vishal Singh