extract the adjacent character of selected letter

Viewed 149

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
6 Answers

With shown samples in awk, could you please try following.

awk '/e/{print substr($0,index($0,"e")-1,1)}' Input_file

Explanation: Adding detailed explanation for above.

awk '             ##Starting awk program from here.
/e/{              ##Looking if current line has e in it then do following.
  print substr($0,index($0,"e")-1,1)
                  ##Printing sub string from starting value of index e-1 and print 1 character from there.
}
' Input_file      ##Mentioning Input_file name here.

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)'

With sed:

sed -nE 's/.*(.)e.*/\1/p' letter.txt

Assuming you have this input file:

cat file
this
is
just
a
test
to
check
if
grep
works
egg
element

You may use this grep + sed solution to find letter or empty string before e:

grep -oE '(^|.)e' file | sed 's/.$//'
t
h
r


l
m

Or alternatively this single awk command should also work:

awk -F 'e' 'NF > 1 {
   for (i=1; i<NF; i++) print substr($i, length($i), 1)
}' file

With GNU awk you can use empty string as FS to split the input as individual characters:

awk -v FS= '/[e]/ {for(i=2;i<=NF;i++) if ($i=="e") print $(i-1)}' file
t
h
r

Excluding "e" at the beginning in the for loop.

  • edited

empty string if e is the first character in the word.

  • For example, this input:
cat file2
grep
erroneously
egg
Wednesday
effectively
awk -v FS= '/^[e]/ {print ""} /[e]/ {for(i=2;i<=NF;i++) if ($i=="e") print $(i-1)}' file2
r

n

W
n

f
v

This might work for you (GNU sed):

sed -nE '/(.)e/{s//\n\1\n/;s/^[^\n]*\n//;P;D}' file

Turn off implicit printing and enable extended regexp -nE.

Focus only on lines that meet the requirements i.e. contain a character before e.

Surround the required character by newlines.

Remove any characters before and including the first newline.

Print the first line (up to the second newline).

Delete the first line (including the newline).

Repeat.

N.B. The solution will print each such character on a separate line.

To print all such characters on their own line, use:

sed -nE '/(.e)/{s//\n\1/g;s/^/e/;s/e[^\n]*\n?//g;s/\B/ /g;p}' file

N.B. Remove the s/\B /g if space separation is not needed.

Related