Search and delete lines matching a pattern along with comments in previous line if any

command-line-interfacescriptingshellunix-shell

I have a requirement to write a shell script in csh to search and delete lines matching a pattern along with comments in previous line if any. For example if my file has the following lines

Shell script
#this is  a test
pattern1
format1
pattern2
format2
#format3
pattern3

If the search pattern is "pattern" The output should be as follows

Shell script
format1
format2

To be more precise the lines which have the pattern and the previous line if it begins with "#" should be deleted

Thanks for the help

Best Answer

First of all nobody should ever use csh for anything - it's outdated and un- (not "under") powered. Secondly, I doubt it's up to the task. Third, it's much more likely that awk, sed or even Perl will be a much better tool for the task.

awk '/^#/ {printf line; line=$0"\n"; next} /pattern/ {line=""} ! /pattern/ {printf line; print; line=""}'

Edit: fixed script to handle comment lines correctly

Related Topic