使用批处理脚本在文本文件中查找字符串

时间:2016-02-08 09:21:27

标签: batch-file

我想在我的批处理脚本中循环我的.txt文件的每一行,并获取其中的每个字符串。

我的文件就像

'string number 1' 'string number 2' 'string number 3'
'string number 11' 'string just string'
//...

我想知道如何让每个字符串都被简单的引号包围。

我希望我足够清楚。

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION 
SET "sourcedir=U:\sourcedir"
SET "destdir=U:\destdir"
SET "outfile=%destdir%\outfile.txt"
SET "filename1=%sourcedir%\q35266036.txt"
(
FOR /f "usebackqdelims=" %%a IN ("%filename1%") DO (
 SET "line=%%a"
 SET "line=!line:'="!"
 FOR %%w IN (!line!) DO echo '%%~w'
)
)>"%outfile%"

GOTO :EOF

您需要更改sourcedirdestdir的设置以适合您的具体情况。

我使用了一个名为q35266036.txt的文件,其中包含我的测试数据。

生成定义为%outfile%

的文件

只需将每个文件读取到%%a,然后输入line进行强制操作。

将每个'替换为

以空格分隔的双引号字符串列表处理。

删除引号并替换为单引号(如果需要)

修改以保存前2项

@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION 
SET "sourcedir=U:\sourcedir"
SET "destdir=U:\destdir"
SET "outfile=%destdir%\outfile.txt"
SET "filename1=%sourcedir%\q35266036.txt"
set "item1="
set "item2="
(
FOR /f "usebackqdelims=" %%a IN ("%filename1%") DO (
 SET "line=%%a"
 SET "line=!line:'="!"
 FOR %%w IN (!line!) DO (
  echo '%%~w'
  if defined item1 if not defined item2 set "item2=%%~w"
  if not defined item1 set "item1=%%~w"
 )
)
)>"%outfile%"

echo item1=%item1%
echo item2=%item2%

GOTO :EOF
相关问题