title: How to remove part of the middle of a line/string by matching two known patterns in front and behind variable text to be removed
body: <p>How to remove part of the middle of a line/string by matching two known patterns, one in front of text to be removed and one behind the text to be removed?</p>
  
  <p>I have a Linux text file with thousands of one line, comma delimited records. unfortunately, all records are not the same format. Each line may have as many as four comma delimited fields of which only the first and last are constant, the two middle fields may, or may not, be present.</p>
  
  <p>Examples of existing line (record) formats. Messy data but the first field is always present, as is the last field, starts with word ADDED.</p>
  
  <pre><code>FNAME LNAME, SOME COMMENT, JOINED DATE, ADDED TO DB DATE
  
  FNAME LNAME, ADDED TO DB DATE
  
  FNAME LNAME, SOME COMMENT, ADDED TO DB DATE
  
  FNAME LNAME, JOINED DATE, ADDED TO DB DATE
  </code></pre>
  
  <p>Objective is to keep field one including the comma, throw away everything following the first comma, keeping the word "ADDED" and everything that follows to the end of line and insert a space between the first comma and the word ADDED.</p>
  
  <p>For each line in parse the file from start of line to the first comma (keep this).</p>
  
  <p>Parse rest of line up to the space before the word “Added” and throw it away. </p>
  
  <p>Keep everything from the space before the word “ADDED” to end of line and concatenate the first part and last part to form one record per line with two fields separated by a comma and a space. </p>
  
  <p>(if record is already in desired format, change nothing)</p>
  
  <p>Final file to look like:</p>
  
  <pre><code>FNAME LNAME, ADDED TO DB DATE
  </code></pre>
  
  <p>or </p>
  
  <pre><code>Fred Flintstone, ADDED on January 1st 2015 By Barney Rubble
  </code></pre>
  
  <p>Thanks!</p>