Insert a string at a specific position in a file with batch script

  • 8 months ago
Comment

ChatGPT
1 / 1

You can use a batch script to insert a string at a specific position in a file by combining various commands such as for, set /p, and redirection. Here's an example script:

batch
@echo off
setlocal enabledelayedexpansion

set "filePath=path\to\your\file.txt"
set "insertText=Inserted Text"
set "insertPos=10" REM Specify the position where you want to insert the text

REM Read the file content up to the insertion position
set "fileContent="
set "lineCount=0"
for /f "delims=" %%a in (%filePath%) do (
set /a "lineCount+=1"
if !lineCount! lss %insertPos% (
set "fileContent=!fileContent!%%a"
) else (
goto :BreakLoop
)
)
:BreakLoop

REM Insert the text at the specified position
echo.%insertText%>>%filePath%
echo.!fileContent!>>%filePath%

echo Text inserted at position %insertPos% in %filePath%
pause

Replace path\to\your\file.txt with the actual path to the file you want to modify, Inserted Text with the text you want to insert, and 10 with the position where you want to insert the text.

This script reads the content of the file up to the insertion position and stores it in a variable (fileContent). It then appends the inserted text and the remaining file content to the file.

Keep in mind that this approach reads and writes the entire file, which may not be efficient for very large files. Additionally, if the file already exists, the script overwrites it. Make sure to back up your file before testing this script on important data.