Deleting First line and last two lines from multiple text files.



  • How i can delete first line and last two lines from multiple text file at once?



  • @R-k said in Deleting First line and last two lines from multiple text files.:

    delete first line and last two lines

    A very interesting problem. It turns out to be fairly simple. It requires use of a regex (regular expression). So the find in Files window needs the search mode set to “regular expression”.

    So with the Find in Files option the entries are:
    Find What:(?-s).+\R(?s)(.+)(?-s)(.+\R){2}
    Replace With:\1
    Use “Replace All” once the selection of files set.

    So what is occurring is:
    (?-s) we do NOT allow the . to include an end of line marker
    .+\R we grab the first line including end of line
    (?s) we change the option so the . DOES include end of line marker
    (.+) we grab everything else (initially), this is saved in group 1
    (?-s) we do NOT allow the . to include an end of line marker
    (.+\R){2} requires that we have the last 2 lines. This requires the previously saved group to give those 2 lines up.
    The replace field tells the system to return the saved group, which will now be minus the last 2 lines. The first line was already grabbed prior to group 1 being saved.

    Note, if the last line is an empty line (zero length line) this will still be counted as 1 of the 2 lines.

    Hopefully this will solve your problem. As always I suggest you have backup copies of the files being edited, and to randomly check some that were worked on just to verify the regex did what you needed.

    Terry



  • Hello, @r-k, @Terry-R and All,

    I found out an other solution, which is the opposite of the @Terry-r’s one : it deletes which is not needed, instead of rewriting which must be kept !

    However, because of some strange behaviours, due to the \A assertion, my solution requires two consecutive regex S/R :

    • The first S/R, below, will replace any possible range of empty line(s), at the very beginning of files, followed with the contents of the first non-empty line with a specific string, not yet present in files. I chose the string X_X_X_X_X_X, but any expression can be used as long as that expression does not exist in all the files scanned !

      • SEARCH (?-s)\A^\R*.+

      • REPLACE X_X_X_X_X_X

    • The second and last S/R, below, will delete the entire line X_X_X_X_X_X, with its line-break, as well as the last two non-empty lines, possibly followed with some true empty lines, at the very end of files

      • SEARCH X_X_X_X_X_X\R|(?-s).+\R.+\R*\z

      • REPLACE Leave EMPTY

    Best Regards,

    guy038


Log in to reply