gpt4 book ai didi

string - 在文本文件中查找具有特殊字符的字符串并在每次出现之前添加换行符

转载 作者:行者123 更新时间:2023-12-02 04:27:00 24 4
gpt4 key购买 nike

我有一个文本文件,它是一个长字符串,如下所示:

ISA*00*GARBAGE~ST*TEST*TEST~CLP*TEST~ST*TEST*TEST~CLP*TEST~ST*TEST*TEST~CLP*TEST~GE*GARBAGE*~   

我需要它看起来像这样:

~ST*TEST*TEST~CLP*TEST
~ST*TEST*TEST~CLP*TEST
~ST*TEST*TEST~CLP*TEST

我首先尝试在每个 ~ST 处添加一行来分割字符串,但我一生都无法做到这一点。我尝试过各种脚本,但我认为查找/替换脚本效果最好。

@echo off
setlocal enabledelayedexpansion
set INTEXTFILE=test.txt
set OUTTEXTFILE=test_out.txt
set SEARCHTEXT=~ST
set REPLACETEXT=~ST

for /f "tokens=1,* delims=~" %%A in ( '"type %INTEXTFILE%"') do (
SET string=%%A
SET modified=!string:%SEARCHTEXT%=%REPLACETEXT%!

echo !modified! >> %OUTTEXTFILE%
)
del %INTEXTFILE%
rename %OUTTEXTFILE% %INTEXTFILE%

在这里找到How to replace substrings in windows batch file

但我陷入困境,因为 (1) 特殊字符 ~ 使代码根本不起作用。它给了我这个结果:

string:~ST=~ST

如果在 "~ST" 周围使用引号,则代码不会执行任何操作。 (2) 我不知道如何在 ~ST 之前添加换行符。

最终任务是在执行所有拆分后删除 ISA*00*blahblahblah~GE*blahblahblah 行。但我陷入了 ~ST 部分的分割。

有什么建议吗?

最佳答案

@echo off
setlocal EnableDelayedExpansion

rem Set next variable to the number of "~" chars that delimit the wanted fields, or more
set "maxTokens=7"
rem Define the delimiters that starts a new field
set "delims=/ST/GE/"

for /F "delims=" %%a in (test.txt) do (
set "line=%%a"
set "field="
rem Process up to maxTokens per line;
rem this is a trick to avoid a call to a subroutine that have a goto loop
for /L %%i in (0,1,%maxTokens%) do if defined line (
for /F "tokens=1* delims=~" %%b in ("!line!") do (
rem Get the first token in the line separated by "~" delimiter
set "token=%%b"
rem ... and update the rest of the line
set "line=%%c"
rem Get the first two chars after "~" token like "ST", "CL" or "GE";
rem if they are "ST" or "GE":
for %%d in ("!token:~0,2!") do if "!delims:/%%~d/=!" neq "%delims%" (
rem Start a new field: show previous one, if any
if defined field echo !field!
if "%%~d" equ "ST" (
set "field=~%%b"
) else (
rem It is "GE": cancel rest of line
set "line="
)
) else (
rem It is "CL" token: join it to current field, if any
if defined field set "field=!field!~%%b"
)
)
)
)

输入:

ISA*00*GARBAGE~ST*TEST1*TEST1~CLP*TEST1~ST*TEST2*TEST2~CLP*TEST2~ST*TEST3*TEST3~CLP*TEST3~GE*GARBAGE*~CLP~TESTX

输出:

~ST*TEST1*TEST1~CLP*TEST1
~ST*TEST2*TEST2~CLP*TEST2
~ST*TEST3*TEST3~CLP*TEST3

关于string - 在文本文件中查找具有特殊字符的字符串并在每次出现之前添加换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34129119/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com