Replace text at specific line number with other text using notepad++

find and replacenotepad

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

Best Answer

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