how to replace a string on the second line in a text file using a batch file?

前端 未结 1 1619
鱼传尺愫
鱼传尺愫 2020-12-21 12:11

Ok so ive been working on a fairly complex batch file that basicly asks the user to create a text file that contains 6 (or more) lines of text. Then it takes that file and c

相关标签:
1条回答
  • 2020-12-21 12:17

    Let me introduce you to my friend, the for loop. Save all the lines the user entered into a single file. I'll call this file input.txt. Use a for loop with the /f switch and the delims= option to loop through every line in the file, and store the lines in the variable %%i. Without delims=, it'd read only until the first whitespace character.

    For each line it reads, do your text substitution. The "gotcha" with batch programming is when you set variables inside a for loop, you have to add the line setlocal enabledelayedexpansion at the top of your file, and use ! instead of % to access the variable contents.

    @echo off
    setlocal enabledelayedexpansion
    for /f "delims=" %%i in (input.txt) do (
    echo translating "%%i"... ^<insert fake delay here^>
    set var=%%i
    set var=!var:a=1 !
    set var=!var:b=2 !
    set var=!var:c=3 !
    set var=!var:d=4 !
    set var=!var:e=5 !
    set var=!var:f=6 !
    set var=!var:g=7 !
    set var=!var:h=8 !
    set var=!var:i=9 !
    set var=!var:j=10 !
    set var=!var:k=11 !
    set var=!var:l=12 !
    set var=!var:m=13 !
    set var=!var:n=14 !
    set var=!var:o=15 !
    set var=!var:p=16 !
    set var=!var:q=17 !
    set var=!var:r=18 !
    set var=!var:s=19 !
    set var=!var:t=20 !
    set var=!var:u=21 !
    set var=!var:v=22 !
    set var=!var:w=23 !
    set var=!var:x=24 !
    set var=!var:y=25 !
    set var=!var:z=26 !
    echo !var!
    )
    

    If input.txt has these contents:

    programable
    this is line 2
    third line
    

    Then the output would look like this:

    C:\batch>encode.cmd
    translating "programable"... <insert fake delay here>
    16 18 15 7 18 1 13 1 2 12 5
    translating "this is line 2"... <insert fake delay here>
    20 8 9 19  9 19  12 9 14 5  2
    translating "third line"... <insert fake delay here>
    20 8 9 18 4  12 9 14 5
    

    As you can see, I left out the fake delay. I like my programs fast. :)

    0 讨论(0)
提交回复
热议问题