使用.bat逐行修改.txt

时间:2018-06-04 16:27:56

标签: batch-file

我有这个.txt文件:

Previsto:  R$ 9.766,53  
Previsto:  R$ 423,65  
Previsto:  R$ 514,51  
Previsto:  R$ 492,63  

所以我需要更改单词" Previsto"换句话说:

Visa: R$ 9.766,53

Elo: R$ 423,65

Hipercard: R$ 514,51

Sorocred: R$ 492,63

我做了这个.bat脚本:

@echo off 
    setlocal enableextensions disabledelayedexpansion
    set "search=%Previsto"
    set "replace=%Visa"
    set "textFile=extract.txt"

    for /f "delims=" %%i in ('type "%textFile%" ^& break ^> "%textFile%" ') do (
        set "line=%i"
        setlocal enabledelayedexpansion
        >>"%textFile%" echo(!line:%search%=%replace%!
        endlocal
    )

但是所有的线路都在取代" Previsto"到"签证" 我不知道如何设置它只改变fisrt线到" Visa"第二行" Elo",thrid" Hipercard"等

我该怎么做?

由于

2 个答案:

答案 0 :(得分:1)

Try like this :

@echo off
setlocal enabledelayedexpansion

set "$file=extract.txt"
set "$search=Previsto"

set $repl[1]=Visa
set $repl[2]=Elo
set $repl[3]=Hipercard
set $repl[4]=Sorocred

set $count=1

(for /f "delims=" %%a in (%$file%) do (
   call:replace "%%a" !$count!
   set/a $count+=1
   )
)>out.txt

echo done..
exit/b

:replace

set "$line=%~1"
set $repl=!$repl[%2]!
set "$line=!$line:%$search%=%$repl%!"
echo !$line!

The ouput file is out.txt

Edit 2

for the blank line after line 1

:replace

set "$line=%~1"
set $repl=!$repl[%2]!
set "$line=!$line:%$search%=%$repl%!"
echo !$line!
if "%2"=="1" echo.

答案 1 :(得分:1)

我和SachaDee有类似的想法,但创建数组的方法不同 没有子程序

    Public roww
Sub Main()
    Dim sht
    roww = InputBox("Start Row", "Row to start", "", 8000, 6000)
    If roww <> "" Then
        Set sht = Sheets("Your sheet")
        'this is a validation
        Do Until sht.Cells(roww, "A").Value = ""
        'this is other optional validation
            If sht.Cells(roww, "Y").Text <> "" Then
                [Perform this action]
                roww = roww + 1
            Else
                roww = roww + 1
            End If
        Loop
    Else
End If
MsgBox ("The Process has been completed")
End Sub

签证后带空白行的示例输出:

:: Q:\Test\2018\06\04\SO_50684988.cmd
@Echo off&SetLocal EnableExtensions EnableDelayedExpansion

Rem Set replace[0..3] to cards
Set i=-1&Set "replace= Visa Elo Hipercard Sorocred"
Set "replace=%replace: ="&Set /a i+=1&Set "replace[!i!]=%"

set "search=Previsto"
set "textFile=extract.txt"
set /A "cnt=pnt=0,i+=1"

(for /f "tokens=1* delims=:" %%A in ('type "%textFile%" ') do (
  if /i "%%A" equ "%search%" call Echo=%%replace[!pnt!]%%:%%B
  if !pnt!==0 Echo=
  Set /A "cnt+=1,pnt=cnt %% i"
) ) >"New_%textFile%

type "New_%textFile%"

该批次将依次替换任意数量的Previsto。