Thursday, November 6, 2014

Sed to modify every 1st and 3rd occurrence

sed 'H;$!d;x;:a;s/word/MATCH/1;s/word/IGNORE/1;s/word/MATCH/1;t a;s/MATCH/words/g;s/IGNORE/word/g' file

Okay, this may seem complicated at first but its simple - this copies all the text into the Hold space, after that it uses a 3 pattern first occurence match to modify the looked for text (word) with a substitute constant (to avoid reprocessing) then loops (t a) back to the label (:a) until the whole file is processed afterward it replaces the substitute constants.

You can use whatever substitute constants (MATCH,IGNORE) you want if those are problem for your data.

No comments:

Post a Comment