1.7.09

The Power of UNIX Shell

Try a program which require 'n' number of lines to be deleted from the file after matching particular string pattern.

General approach will be like this:
1. Find the total line number 'X' in given file
2. Find a line number 'N' which matches a given pattern.
3. copy all the lines from line#1 to line#(N-1) to the temp file
4. skip next 'n' number of lines
5. copy and append from line#(N+n) line#X to the temp file
6. rename temp file to the given file

This is little complex to implement in C/C++. It'll take around 20-30 lines of code to write in C/C++. But it is just a matter of 2 lines in UNIX. And here it is how you do it:

If you have find the all the line numbers required then
1. To copy all the lines from line#1 to line#(N-1)
head -[first N-1 lines to be copied] [given_file] > [temp_file]

2. Just calculate the line numbers to be copied from the EOF (End-of-File)
tail -[last X-N-n+1 lines to be copied] [given_file] >> [temp_file]

4 comments:

Bipul said...

grep -v "string to match" [source file name] > [tmp filename]

mv [tmp filename] [source file name]

Bipul said...

advantage is you use less file i/o for bigger files
grep gives u ability to use RegEx much more powerful.

Bipul said...

u r solution does not determine the line number at which the string pattern is found so it will take 3 steps not 2

Pawan B. said...

Thanks Bipul for better way to handle the problem....