我想使用批处理脚本在特定行(例如n(12或23或其他一些数字))中插入一个字符串“ hello”。我知道批处理脚本不好,但是很遗憾,此要求是批处理脚本。
这就是我尝试过的
@echo off
setlocal enableextensions disabledelayedexpansion
set "nthline=TEXT"
(for /f "usebackq tokens=* delims=" %%a in (c.txt) do (
echo(%%a
if defined nthline (
echo(%nthline%
set "nthline="
)
))
我从here获得的这段代码,但仅插入到第二行,我无法超越此行。
此处是文本文件包含的内容
aaaa
bbbb
cccc
dddd
ffff
gggg
hhhh
它将字符串插入到aaaa之后。我如何使其插入bbbb或ffff我是批处理脚本的新手,所以对您的帮助非常感谢
答案 0 :(得分:2)
您发布的代码旨在在第一行之后插入额外的一行。
要在某一点插入,您需要以某种方式预定义目标行号和行号,然后比较这些数字是否相等,并在以下脚本中返回额外的文本行:
@echo off
setlocal EnableExtensions DisableDelayedExpansion
rem // Define constante here:
set "_FILE=c.txt" & rem // (text file to insert a line of text into)
set "_TEXT=hello" & rem // (text of the inserted line)
set /A "_NUM=4" & rem // (number of the line where the new line is inserted)
set "_REPLAC=#" & rem // (set to anything to replace the target line, or to nothing to keep it)
set "_TMPF=%TEMP%\%~n0_%RANDOM%.tmp" & rem // (path and name of temporary file)
rem // Write result into temporary file:
> "%_TMPF%" (
rem // Loop through all lines of the text file, each with a preceding line number:
for /F "delims=" %%L in ('findstr /N "^" "%_FILE%"') do (
rem // Store current line including preceding line number to a variable:
set "LINE=%%L"
rem // Set the current line number to another variable:
set /A "LNUM=%%L"
rem // Toggle delayed expansion to avoid trouble with `!`:
setlocal EnableDelayedExpansion
rem // Compare current line number with predefined one:
if !LMUN! equ %_NUM% (
rem // Line numbers match, so return extra line of text:
echo(!_TEXT!
rem // Return original line (without preceding line number) only if it is not to be replaced:
if not defined _REPLAC echo(!LINE:*:=!
) else (
rem // Line numbers do not match, so return original line (without preceding line number) anyway:
echo(!LINE:*:=!
)
endlocal
)
)
rem // Move temporary file onto original one:
move /Y "%_TMPF%" "%_FILE%"
endlocal
exit /B