使用批处理编程在第2行之后插入特定文本 [英] insert specific text after line 2 with batch programming

查看:195
本文介绍了使用批处理编程在第2行之后插入特定文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的文件

I have a file that looks like this

0181830207709014000015576526S00000140000014000001242017
0052500056661095000015576527S00000950000095000001242017
0157020294103030000015576528S00000300000030000001242017
2397870060994031500015576529S00000315000031500001242017
2466260219154015000015576530S00000150000015000001242017

0181830207709014000015576526S00000140000014000001242017
0052500056661095000015576527S00000950000095000001242017
0157020294103030000015576528S00000300000030000001242017
2397870060994031500015576529S00000315000031500001242017
2466260219154015000015576530S00000150000015000001242017

我需要在第2行之后插入一个称为插入新行"的特定文本,并将输出重定向到具有不同文件名的新文件.我该如何使用批处理程序解决此问题.,

I need to insert a specific text called "insert me a new line" after line2 and redirect the output to a new file with a different file name. how can i solve this using batch programming.,

推荐答案

使用Findstr /N为文件的行编号

> findstr /N ".*" test.txt
1:0181830207709014000015576526S00000140000014000001242017
2:0052500056661095000015576527S00000950000095000001242017
3:0157020294103030000015576528S00000300000030000001242017
4:2397870060994031500015576529S00000315000031500001242017
5:2466260219154015000015576530S00000150000015000001242017

For /f循环以解析输出,在冒号处将其拆分为数字的vars %%A和行内容的%%B.如果数字是2,请插入多余的行.

And a For /f loop to parse the output, splitting at the colon into vars %%A for the number and %%B for the line content. If the number is 2 insert the extra line.

@Echo off
Set "File=Test.txt"
Set "NewFile=TestNew.txt"
(
  For /f "Tokens=1*Delims=:" %%A in (
    'Findstr /N ".*" "%File%"'
  ) Do If %%A Equ 2 (
    Echo:insert me a new line before
    Echo:%%B
    Echo:insert me a new line below
  ) Else (
    Echo:%%B
  )
) >"%NewFile%"

EDIT 更改了后续读者的逻辑.样本输出:

EDIT changed the logic for followup readers. Sample Output:

> type TestNew.txt
0181830207709014000015576526S00000140000014000001242017
insert me a new line before
0052500056661095000015576527S00000950000095000001242017
insert me a new line below
0157020294103030000015576528S00000300000030000001242017
2397870060994031500015576529S00000315000031500001242017
2466260219154015000015576530S00000150000015000001242017

这篇关于使用批处理编程在第2行之后插入特定文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆