1

我会尝试解释我要完成的工作,但最好用一个例子来解释。

我试图改变这样的事情:

Example Line 1
-Sub line X
-Sub line Y
-Sub line Z
Example Line 2
-Sub line X
-Sub line Y
-Sub line Z
Example Line 3
-Sub line X
-Sub line Y
-Sub line Z

并像这样插入行:

Example Line 1
-Sub line X
-Sub line Y
-Sub line Z
Example Line 2
-Sub line X
-Sub line Y
-Inserted line 1
-Inserted line 2
-Inserted line 3
-Sub line Z
Example Line 3
-Sub line X
-Sub line Y
-Sub line Z

因此,虽然子行可能与其他示例行相同,但示例行将始终不同。我想知道是否有办法找到特定的示例行(在这种情况下Example Line 2),然后Sub line Y在其中找到,然后在之后(或之前)插入代码?

或者我是否缺少完全不同的逻辑

仅供参考 - 使用本机 MS-DOS 创建此批处理脚本。感谢帮助

4

2 回答 2

0

我假设文本在文件中。

如果要在命令中拼出插入的行:

sed '/Example Line 2/,/Example Line 3/{/-Sub line Z/i\
-Inserted line 1\
-Inserted line 2\
-Inserted line 3
;}' filename

如果您想从文件中读取插入的行(例如“newfile”):

sed '/Example Line 2/,/Example Line 3/{/-Sub line Y/ r newfile
}' filename
于 2013-08-03T00:17:47.960 回答
0
@echo off
setlocal EnableDelayedExpansion
set section=Example line 2
set line=-Sub line Y

rem Search for "line" line *after* "section" line
for /F "tokens=1* delims=:" %%a in ('findstr /N /C:"%section%" /C:"%line%" theFile.txt') do (
   if not defined StartSection (
      if "%%b" equ "%section%" set StartSection=%%a
   ) else (
      if not defined TargetLine (
         if "%%b" equ "%line%" set TargetLine=%%a& goto continue
      )
   )
)
echo Target line "%line%" into section "%section%" not found
goto :EOF

:continue

for /F "tokens=1* delims=:" %%a in ('findstr /N "^" theFile.txt') do (
   echo(%%b
   if %%a equ %TargetLine% (
      echo -Inserted line 1
      echo -Inserted line 2
      echo -Inserted line 3
   )
)
于 2013-08-03T04:42:34.370 回答