New line as a delimeter of FOR loop

﹥>﹥吖頭↗ 提交于 2020-01-11 10:22:32

问题


I am new to batch script, and I am trying to parse a file that has key value (kind) of pairs delimited by new line. For example:

the value of abc
1234
the value of def
5678
the value of ghi
9876

I would like to read this file using new line as delimited so that I can access the values.

Something like

for /f "tokens=1,2,3 delims='\n'" %%i in ('findstr /C:the value of abc 'filepath') do echo %%j

回答1:


You can't set 'new line' as delimiter. Try this:

@echo off &setlocal
for /f "tokens=1*delims=:" %%i in ('findstr /NC:"the value of abc" "filepath"') do set /a count=%%i
if defined count for /f "skip=%count%tokens=1*delims=:" %%i in ('findstr /N "^" "filepath"') do if not defined value set "value=%%j"
echo.%value%
endlocal



回答2:


@ECHO OFF
SETLOCAL
SET "prevline="
FOR /f "delims=" %%z IN (tvabc.txt) DO (
 IF DEFINED prevline (
  FOR /f "tokens=1-6" %%a IN ('echo %%prevline%% %%z') DO (
   ECHO %%a %%b %%c %%d %%e %%f
   )
  SET "prevline="
  ) ELSE (SET prevline=%%z)
)

should do the job, if you require each token from two successive lines to be output. Would be much easier if we had a listing of the required output rather than having to guess from code that doesn't work.

Essentially, this code saves the contents of one line then detects that the second has been read by the fact that the variable holding the previous line is defined. Under those circumstances, for/f is used to tokenise the concatenation of the two lines.




回答3:


I just put it here as an option:

for /F delims^=^ eol^= %%i in ('findstr /C:the value of abc 'filepath') do echo %%i



回答4:


Not sure what you're going to do with those Name/Value pairs after you get them, but if you're going to do it in Powershell, do it right and start by creating objects:

$file = 'c:\somedir\somefile.txt'

[regex]$regex = @'
(?ms)the value of (\S+)
(\d+)
'@

#Choose one
$text = Get-Content $file -Raw  # V3 Only
$text = [IO.File]::ReadAllText($file)  # V2 or V3


$regex.matches($text) |
foreach {
   New-object PSObject -Property @{
                                   Name = $_.groups[1].value
                                   Value = $_.groups[2].value
                                  }
        }|
  Select Name,Value |
  Format-Table -AutoSize

Name Value
---- -----
abc  1234 
def  5678 
ghi  9876 



回答5:


What do you think of that? In powershell:

(get-content .\essai.txt)[(Select-String .\essai.txt -Pattern "the value of abc").LineNumber]

It displays the next line after the pattern.




回答6:


I normally use the given batch command, to read each line in file

FOR /F "delims=" %%G IN (test.txt) DO (
    ECHO %%G
)

Here, "delim=" does the trick.



来源:https://stackoverflow.com/questions/15641301/new-line-as-a-delimeter-of-for-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!