I'm trying to find all words in which my initials show up not necessarily consecutively.

My first initial should start the word.

My last initial should end the word.

My middle initial is somewhere in between the word


grep '^j.*x$' file

( j is first initial, t would be middle, x is the end of the word )

  • If your initials are jx then there's no reason why that code won't work. Are you trying to find lines where that appears or just the words/strings? – Nasir Riley Mar 24 at 21:20

Well, you would start with


But the .* bits would match anything. So instead restrict those parts to only match letters:


The [[:alpha:]] thing is a POSIX character class that is roughly the same as [A-Za-z], i.e. any alphabetic character.

That's you pattern. Then ask grep nicely to only return complete words. You do that with the -w option. That would restrict the matches to substrings on each line that are delimited by non-word characters such as spaces, or at the start or end of the line.

Add -i if you want to do case-insensitive matching.

If you want only the bits of each line that actually matches the pattern and not the whole line, additionally use -o.

You'll end up with

grep -i -o -w 'j[[:alpha:]]*t[[:alpha:]]*x'


$ grep -i -o -w 'j[[:alpha:]]*t[[:alpha:]]*x' /usr/share/dict/words
  • what are alpha things for? – Joshua Cormier Mar 24 at 21:23
  • @JoshuaCormier It's like [A-za-z], which you could also use, but it assumes the C locale (ASCII characters) whereas [A-Za-z] don't and could match other characters too depeding on the locale. – Kusalananda Mar 24 at 21:25
  • thank you very much!! with your help i figured out the syntax i was looking for! – Joshua Cormier Mar 24 at 21:28
  • @JoshuaCormier: In case you don’t get the point of Kusalananda’s explanation: it is that a line containing (for example) job to fix would match j.*t.*x, or even your ^j.*t.*x$ variation, because . matches any character (except for newline), so ob  (with the trailing space) and o fi would both match .*. Also, you don’t say whether your file has one word per line.  If it said my favorite toy was a jackinthebox, your ^j.*t.*x$ pattern would fail to find it, because the j isn’t at the beginning of the line. – G-Man Apr 1 at 19:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.