在批处理脚本中读取以空格分隔的单词 [英] Read words separated by space in a batch script
问题描述
我需要在批处理脚本中逐字读取文本文件的内容.单词之间用空格隔开.我尝试过此方法,但是它不起作用,它只使用第一个单词:
I need to read the content of a text file word by word, in a batch script. The words are space separated. I tried this but it doesn't work, it only takes the first word:
for /f "delims= " %%i in (%OUTPUT_FILE%) do echo %%i
我也尝试过此方法,但也无法正常工作
I also tried this but doesn't work also:
for /f "tokens=* delims= " %%i in (%OUTPUT_FILE%) do echo %%i
推荐答案
这里是一个纯批处理解决方案,应该能够处理文件中的任何内容.它使用外部FOR/F读取每一行,并用换行符替换每个空格.它将读取每个带有内部FOR/F的结果行(单词).
Here is a pure batch solution that should be able to handle any content in your file. It reads each line with an outer FOR /F, and replaces each space with a newline character. It reads each resulting line (word) with an inner FOR /F.
@echo off
setlocal disableDelayedExpansion
:: Define LF to contain a newline character
set LF=^
:: Above 2 blank lines are critical - DO NOT REMOVE
for /f "eol= tokens=*" %%A in (%OUTPUT_FILE%) do (
set "ln=%%A"
setlocal enableDelayedExpansion
for %%L in ("!LF!") do for /f "eol= " %%W in ("!ln: =%%~L!") do echo %%W
endlocal
)
如果使用称为REPL.BAT的混合JScript/batch实用程序执行正则表达式搜索和替换,则生活会简单得多.在stdin上并将结果写入stdout.
Life is much simpler if you use a hybrid JScript/batch utility called REPL.BAT that performs regex search and replace on stdin and writes the result to stdout.
假设REPL.BAT位于当前文件夹中,或者更好的是位于PATH中的某个位置:
Assuming REPL.BAT is in your current folder, or better yet, somewhere within your PATH:
for /f "eol= " %%W in ('repl " " "\n" x ^<%OUTPUT_FILE%') do echo %%W
这篇关于在批处理脚本中读取以空格分隔的单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!