New line as a delimeter of FOR loop

2020-04-10 02:29发布

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

6条回答
Root(大扎)
2楼-- · 2020-04-10 02:51
@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楼-- · 2020-04-10 02:53

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
查看更多
成全新的幸福
4楼-- · 2020-04-10 02:57

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.

查看更多
\"骚年 ilove
5楼-- · 2020-04-10 03:04

I just put it here as an option:

for /F delims^=^ eol^= %%i in ('findstr /C:the value of abc 'filepath') do echo %%i
查看更多
霸刀☆藐视天下
6楼-- · 2020-04-10 03:08

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 
查看更多
ら.Afraid
7楼-- · 2020-04-10 03:11

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.

查看更多
登录 后发表回答