我有一个包含行的文本文件:
08-09 15:39:38.236 D/MVSDKTutorialBasicOpenCloseFileLoop(12054): availableMemory = 636
我需要获得636值,直到我使用它为止:
for /f "tokens=6-8" %%i in (D:\Roey\Jen2\OpenCloseFileLoop\Results\Logcat\firstline.txt) do set revision=%%i
问题是该线有多余的空间(2054) - 它不起作用(我得=),总是得到最后一列的任何方式?
答案 0 :(得分:3)
行中的最后一个元素:
for /F "delims=" %%a in (file.txt) do for %%b in (%%a) do set "revision=%%b"
答案 1 :(得分:2)
明智地选择你的delims:
for /f "tokens=2 delims==" %%a in (file.txt) do set revision=%%a
REM remove any spaces:
set revision=%revision: =%
答案 2 :(得分:0)
如果您事先不知道分隔项目的数量,可以使用以下代码段,假设文本文件不包含任何全局通配符*
和?
:
@echo off
setlocal EnableExtensions DisableDelayedExpansion
rem /* Define constants here: */
set "FILE=D:\Roey\Jen2\OpenCloseFileLoop\Results\Logcat\firstline.txt"
set "DELIM= " & rem // (define a single character here only)
rem // Walk through the text file line by line:
for /F usebackq^ delims^=^ eol^= %%L in ("%FILE%") do (
set "LINE=%%L"
rem // Toggle delayed expansion to avoid loss of `!`:
setlocal EnableDelayedExpansion
rem // Double each `"` intermittently:
set "LINE=!LINE:"=""!^" & rem "
rem /* Enclose the entire line string within `""` and replace
rem each delimiter by `"` + SPACE + `"`; this results in a
rem SPACE-delimited list with each item enclosed within `""`: */
set "LINE="!LINE:%DELIM%=" "!""
rem /* Iterate through the built list using a standard `for` loop;
rem this works only in case no `*` or `?` occur in the string,
rem because `for` would consider them as global wildcards and
rem access the file system and through file-not-found errors: */
for %%I in (!LINE!) do (
endlocal
rem /* Save item in variable (overwrite previous one, so
rem last item is retrieved), and remove surrounding `""`: */
if not "%%~I"=="" set "LAST=%%~I"
setlocal EnableDelayedExpansion
)
rem // Return last item per line, revert doubling `"`:
if defined LAST echo(!LAST:""=^"!
endlocal
)
rem // Return last item of last line, revert doubling `"`:
setlocal EnableDelayedExpansion
if defined LAST echo(!LAST:""=^"!
endlocal
endlocal
exit /B