 <p><code>awk '/^INSERT|^UPDATE|^DELETE/{i=1} /;/{i=0} {printf("%s ",$0);if(!i) print""}' &lt;filename&gt;</code> this will find the Keywords and then set a flag, which will be reset only when a <code>;</code> is found. Now till the flag is set, newline won't be printed. So it will take care if the <code>;</code> is present in the same line, if any other words are there without <code>;</code>, it will not touch those</p> <p>Experiment</p> <pre><code>[[bash_prompt$]]$ cat log INSERT INTO EMP; (EMP,ENAME) VALUES ('1', 'John'); set term off; UPDATE EMP SET ENAME='Samantha' WHERE DEPT=20; INSERT INTO EMP (EMP,ENAME) VALUES ('1', 'John'); [[bash_prompt$]]$ awk '/^INSERT|^UPDATE|^DELETE/{i=1} /;/{i=0} \ {printf("%s ",$0);if(!i) print""}' log INSERT INTO EMP; (EMP,ENAME) VALUES ('1', 'John'); set term off; UPDATE EMP SET ENAME='Samantha' WHERE DEPT=20; INSERT INTO EMP (EMP,ENAME) VALUES ('1', 'John'); </code></pre>