Replacing multiple lines in a file

  • 8 months ago
Comment

ChatGPT
1 / 1

If you need to replace multiple lines in a file using a script, you can achieve this using various programming languages. Here's an example using Python:

Let's say you have a file named input.txt with the following content:

mathematica
Line 1
Line 2
Line 3
Line 4
Line 5

And you want to replace lines 2 to 4 with new lines:

mathematica
New Line 2
New Line 3
New Line 4

Here's a Python script that reads the file, replaces the lines, and writes the modified content back to the file:

python
# ReplaceLines.py

# Define the range of lines to replace
start_line = 2
end_line = 4

# Define the replacement lines
replacement_lines = [
"New Line 2",
"New Line 3",
"New Line 4"
]

# Read the content of the file
with open("input.txt", "r") as file:
lines = file.readlines()

# Modify the lines
for i in range(start_line - 1, end_line):
lines[i] = replacement_lines[i - start_line + 1] + "\n"

# Write the modified content back to the file
with open("input.txt", "w") as file:
file.writelines(lines)

Run this script, and it will replace the specified lines in the input.txt file with the new lines.

Remember to adjust the file paths and line numbers according to your requirements. Additionally, this example assumes that the replacement lines are provided in a list. You can customize the script to suit your specific needs.

Note: Make sure to have a backup of your original file before running the script to avoid accidentally losing data.