1

I have hundreds of input files that are very similar, but contain slight differences. I want to replace every line 4 in all open documents with another line of text. The search and replace function does not work, as line 4 has different text in the various files.

A crude example of what I want to do is shown below:

file A line 4: some text

file B line 4: different text

replace line 4 with: new text

2 Answers 2

4

I would say that Notepad++ is not the tool to do this job.

Instead, I would suggest that you use a scripting language of some kind to:

  • iterate the files
  • then iterate the lines
  • replace the single line (if it exists)
  • then save the file.

Here's a PowerShell script that will do that:

# Set by user to their needs.
$filesToCheck = "C:\path\to\files\*.txt"
$lineToChange = 4
$replacementLineText = "New Text"

# Gather list of files based on the path (and mask) provided by user.
$files = gci $filesToCheck

# Iterate over each file.
foreach ($file in $files) {

    # Load the contents of the current file.
    $contents = Get-Content $file

    # Iterate over each line in the current file.
    for ($i = 0; $i -le ($contents.Length - 1); $i++) {

        # Are we on the line that the user wants to replace?
        if ($i -eq ($lineToChange - 1)) {

            # Replace the line with the Replacement Line Text.
            $contents[$i] = $replacementLineText

            # Save changed content back to file.
            Set-Content $file $contents
        }
    }
}
1
  • Why iterate every line instead of doing $contents[$linetochange] ?
    – jiggunjer
    Sep 5, 2017 at 13:30
0

Search for regular expression:

^(([^\n]*\n){n})[^\n]+

where "n" is the number of the line to skip, and replace with

\1text

where text is the new text you want on line n+1.

Adapt the search expression with the proper EOL, I used "\n" that is for UNIX.

Explanation:

This script looks for the first n lines to skip:

([^\n]*\n){n}

and saves them in a buffer (brackets enclosing them:

(([^\n]*\n){n})

Then followed by the another line (not empty):

([^\n]+)

then replaces with the content of the buffer

\1

followed by your new text.

\1text

Additional info:

If you want to be extra sure, and the files are not big, you can also match the lines following:

^(([^\n]*\n){n})[^\n]+(\n([^\n]*\n){n})

replace with

\1text\3

Not tested.

1
  • 1
    ". matches newline enabled" is useless, you don't have any dots in your regex.
    – Toto
    Sep 5, 2017 at 12:08

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .