首页 > 解决方案 > 如何从批处理文件中的多行获取此文本

问题描述

我有一个逐行的文本文件(Myfile.txt),它很长并且居中,如下所示

...","ItemPrice":17000.0,"MustPay":17000.0,"PaywithCash":17000.0,"etc...
...","ItemPrice":900.0,"MustPay":900.0,"PaywithCash":900.0,"etc...
...","ItemPrice":1400.0,"MustPay":1400.0,"PaywithCash":1400.0,"etc...

所以我想得到单词“PayWithCash”后面的数字:例如第一行是数字17000等到下一行,并将其保存到一个新的文本文件“result.txt”

1700
900
1400

我已经尝试了几个代码,包括如下

echo off 
SETLOCAL EnableDelayedExpansion
for /f "delims=" %%a in ('type Myfile.txt^|find "PayWithCash:"') do (
  set "line=%%a"
  set "line=!line:*PayWithCash =!
  set /a "last=!line:~1!" 2>nul
)
echo %last% >> result.txt

是的,我仍然无法得到想要的结果,你能帮帮我吗?

我用谷歌翻译,希望你能理解

标签: batch-filecmd

解决方案


更正PayWithCash数据中的正确大小写,PaywithCash或添加/i开关以find使匹配不区分大小写。

按照@Compo 的建议删除冒号。

删除语句中的Spaceafter PayWithCash,因为数据中没有。setSpace

由于line现在将开始结果,因此":您需要使用line:~2

我使用的测试代码:

@ECHO OFF
SETLOCAL EnableDelayedExpansion
SET "sourcedir=U:\sourcedir"
SET "destdir=U:\destdir"
SET "filename1=%sourcedir%\q64838297.txt"
SET "outfile=%destdir%\outfile.txt"

(
for /f "delims=" %%a in ('type "%filename1%"^|find /i "PayWithCash"') do (
  set "line=%%a"
  set "line=!line:*PayWithCash=!"
  set /a "last=!line:~2!" 2>nul

  echo !last!
)
)>"%outfile%"

TYPE "%outfile%"

GOTO :EOF

您将需要更改设置sourcedirdestdir适应您的情况。该清单使用适合我的系统的设置。

我使用了一个名为q64838297.txt包含您的数据的文件进行测试。

生成定义为的文件%outfile%

结果:

17000
900
1400

推荐阅读