I have a huge text file called dictionary.txt with entries like

    ABC_SEQ_NUM This represents....
    ABC_RANK This represents....
    ABC_BSC_ID This represents...
    PQR_TA_DATE_AF This represents...
    XYZ_C_ID This represents...

In another file, I have the source for a program that is using some of these abbreviations as part of its variable names. The variable names often use the above entries as follows


So I am not able to simply search for TMP_ABC_SEQ_NUM using grep, because it would return no match. However, the last part of the variable name ("ABC_SEQ_NUM") is actually present in the text file.

So I would like to say something like

      grep (longest match for) TMP_ABC_SEQ_NUM in dictionary.txt

So that it would return the match for


How to write such a command?

  • Related: stackoverflow.com/a/34466302/785213. That matches the shortest prefix, and would require GNU grep for its -P flag (Perl-compatible regular expression). I didn't try to make it work for your use case—since what I needed was a prefix match—but there's at least a chance that the regexp from that solution could be adapted to your needs as well.
    – Kevin E
    Commented Nov 15, 2022 at 18:01

3 Answers 3


This would try to match from the beginning:

for n in $(seq 0 ${#t})
  grep ${t:n} dictionary.txt && break

This searches for the longest sequence, no matter where it starts:

for len in $(seq ${#t} -1 3)
   for start in $(seq 0 $((${#t}-len)))
       grep ${t:start:len} dictionary.txt && break 2

requirement: A bash-like shell, available here: native win32 ports of many GNU-utils, like sh.exe, grep, sed, awk, bc, cat, tac, rev, col, cut, ...


A possible approach, to shorten the string from the head until it matches:

while ! grep "$string" dictionary.txt; do 
  # remove the shortest leading string ending with "_"
  • Would this work under Windows? I am using grep under Windows.
    – CodeBlue
    Commented Apr 2, 2012 at 14:29
  • @CodeBlue: it do not depends on grep, but on the availability of a POSIX shell. It is surely available through Cygwin.
    – enzotib
    Commented Apr 2, 2012 at 14:30
  • What if the string was FOO_ABQ_SEQ_NUM_BAR? Commented Apr 2, 2012 at 23:18
  • @Gilles: the problem does not seem to be well defined, so mine was only a tentative solution
    – enzotib
    Commented Apr 3, 2012 at 5:45

Could you reverse the way you're looking at this? Rather than looking for TMP_ABQ_SEQ_NUM in dictionary.txt, could you not look for the first field for each line in dictionary.txt (the ABQ_SEQ_NUM) in the source file?

If this is the case, the following should work

for i in $(awk '{print $1}' dictionary.txt) do
    grep $i $1

Pass the above script the name of the file you want to check for sequences present in dictionary.txt. Apologies if this isn't what you wanted.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .