title: Linux: remove strings from list if they have substrings elsewhere in list
body: <p>I would like to take a list of strings and keep only those that have no substrings elsewhere in the list. To illustrate, I have this list:</p>
  
  <pre><code>apple
  applesauce
  kiwi
  mango
  mangoes
  mangosteen
  oranges
  pineapples
  </code></pre>
  
  <p>I want to reduce it down to a list of strings which do not have any substrings elsewhere in the list. So, the resulting list would be:</p>
  
  <pre><code>apple
  kiwi
  mango
  oranges
  </code></pre>
  
  <p>Note that <code>applesauce</code> and <code>pineapples</code> were removed because <code>apple</code> is elsewhere in the list and is a substring of both those words. </p>
  
  <p>I found a similar question <a href="https://stackoverflow.com/questions/21238090/use-grep-to-remove-words-from-dictionary-whose-roots-are-already-present">here</a> but it seems to be aimed specifically at prefixes, e.g. <code>ablaze, able, abler, ablest</code>. Based on that method, I tried the following with a pre-sorted copy of my list and it just printed the entire list, without even removing <code>applesauce</code> which I thought it would:</p>
  
  <pre><code>awk '$1~r &amp;&amp; p in k { next } { k[$1]++; print; r= "^" $1; p=$1 }' fruitsorted.txt
  </code></pre>
  
  <p>Even if it had worked as I expected, it would still miss <code>pineapple</code> in my list. </p>
  
  <p>Note that in an extreme case, if the list contained all the letters of the alphabet (or ASCII char set I guess) each on a separate line, then regardless of what else was in the list, the ouput would just be the alphabet/ char set. </p>
  
  <p>Also, my starting list is unsorted. I don't really care if the resulting list is sorted although that's obviously trivial with <code>sort</code>. </p>
  
  <p>Ideally I would like a somewhat compact shell command/ sequence of stuff like grep/ sort/ awk, as opposed to a longer form Perl/ Python/ whatever script which I already know how to implement. </p>
  
  <p>Thanks. </p>
  
  <p><strong>Update</strong></p>
  
  <p>As pointed out by Ed Morton below, even sorting the list may mess up some basic approaches, e.g. in the following example, approaches that are assuming a sorted list will probably fail to remove <code>berryplum</code> since its substring <code>plum</code> comes after it. The second approach shown by 123 handles this case. </p>
  
  <pre><code>apple
  applesauce
  berryplum
  kiwi
  mango
  mangoes
  mangosteen
  oranges
  pineapples
  plum
  </code></pre>