Insert line in a file with batch script

时间:2017-07-12 08:05:27

标签: batch-file

I want to insert an import in all my java classes, in order to do that I need a batch script. I have already made this :

SETLOCAL ENABLEDELAYEDEXPANSION

set inputFile=C:\Utilisateurs\a669884\Documents\script.txt
set outputFile=C:\Utilisateurs\a669884\Documents\script.txt
set "_strInsert=import java.test"
set "_strFind=import java.Interceptors.RunTimeExceptionInterceptor"
set i=0

FOR /F "usebackq tokens=1 delims=[]" %%A IN (`FIND /N "%_strFind%" 
"%inputFile%"`) DO (set _strNum=%%A)
FOR /F "usebackq delims=" %%A IN ("%inputFile%") DO (
set /a i = !i! + 1
ECHO %%A>>"%outputFile%"
IF [!i!] == [%_strNum%] (ECHO %_strInsert%>>"%outputFile%")
)

In my script.txt i have this at the beginning (without the batch) :

import java.Interceptors.RunTimeExceptionInterceptor

Problem is that after starting the batch, I find a copy of the line that I search+ the line that I want to add :

 import java.Interceptors.RunTimeExceptionInterceptorimport 
    java.Interceptors.RunTimeExceptionInterceptor
    import java.test

Just like this... Can you help me in order to have only the line that i search + the line that I want to add in the txt, without the copy of the first line Thank you very much, Seb

1 个答案:

答案 0 :(得分:0)

使用昨天的代码

插入一组[字符串] [s]
if "%%i "=="!line:%search%=%replace%!" (
 >>%%a echo(!line!
) else (
 >>%%a echo(replacement line 1
 >>%%a echo(replacement line 2
 >>%%a echo(replacement line 3
 >>%%a echo(replacement line 4
)

如果您愿意,您的replace字符串可能为空。这个想法只是使用相同的技术(所以你可以在线内替换或完全替换线)

replacement line *对于空行可能只是 nothing

另一种技术是

if "%%i "=="!line:%search%=%replace%!" (
 >>%%a echo(!line!
) else (
 >>%%a type filecontainingreplacementlinesequence.txt
)

同样,这只是使用相同的技术。

if "%%i "=="%search% " (

也可用于检测重要线。