Replace/delete 'n'th lines within files

Find, replace, find in files, replace in files, regular expressions

Replace/delete 'n'th lines within files

Postby DIV » Thu Nov 17, 2011 1:34 am

Hello,

I have a problem, I want to replace/delete "n"th lines within 500+ files.

For example how to remove/replace 51th line of the file.
OR
How can I delete everything after 51th line.

I know its possible with regular expressions, but I don't know how to.


*Nothing identical in all files.

Thanks.
DIV
Newbie
 
Posts: 2
Joined: Mon May 17, 2010 2:26 am

Re: Replace/delete 'n'th lines within files

Postby Mofi » Thu Nov 17, 2011 1:55 pm

It is perhaps possible to use Replace in Files command for what you want, but Replace in Files is not only executed once on a file which makes the replace difficult. Also it is not really clear for me what you want.

How to remove/replace 51th line of the file can be interpreted as:

  • Delete only line 51 in every file, or
  • delete line 51, 102, 153, ... in every file (every 51th line).
Searching with the Perl regular expression engine for ((?:.*\r\n){50}).*\r\n([^ÿ]+) and using as replace string \1\2 results in deleting only line 51 in every file as long as the file does not contain character ÿ and the file is small. The number of characters which can be tagged (marked) is not unlimited.

Searching for ((?:.*\r\n){50}).*\r\n and using as replace string just \1 results in deleting line 51, 102, 153, ... in a file.

And last searching for ((?:.*\r\n){51})[^ÿ]+ and using as replace string again just \1 results in deleting everything after line 51 in a file as long as the file does not contain character ÿ and the file is small.

The Perl regular expression search strings as posted here are for files with DOS line terminators. Just \n must be used instead of \r\n for files with UNIX line terminators.
User avatar
Mofi
Grand Master
Grand Master
 
Posts: 4049
Joined: Thu Jul 29, 2004 11:00 pm
Location: Vienna

Re: Replace/delete 'n'th lines within files

Postby DIV » Thu Nov 17, 2011 4:45 pm

Thanks You Very Much Mofi Sir.

You always inspire me the way you explain solution..........

I am grateful to you for your help.
DIV
Newbie
 
Posts: 2
Joined: Mon May 17, 2010 2:26 am


Return to Find/Replace/Regular Expressions