[英]For command token doesn't work when there are empty fields in the record
I am trying to extract the values from the third field of a file which has data records.我正在尝试从具有数据记录的文件的第三个字段中提取值。
The fields are separated by vertical bar characters:这些字段由竖线字符分隔:
9001||10454145||60|60
9001|234467|10454145||60|60
9001|234457|10454145||60|60
Command is -命令是 -
for /f "tokens=3 delims=|" %%A IN ('Findstr /i "9001" .\itemloc\%%~nf.dat') do (
echo %%A >> log.txt
)
But the output I am getting is但是我得到的 output 是
60
10454145
10454145
The empty fields are messing up my output. Any suggestions how to make the for
token
work with empty fields in the record?空字段弄乱了我的 output。有什么建议可以使
for
token
与记录中的空字段一起工作吗?
@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
rem The following settings for the directories and filenames are names
rem that I use for testing and deliberately includes spaces to make sure
rem that the process works using such names. These will need to be changed to suit your situation.
SET "sourcedir=u:\your files"
SET "destdir=u:\your results"
SET "filename1=%sourcedir%\q75199035.txt"
SET "outfile=%destdir%\outfile.txt"
(
FOR /f "usebackqtokens=1*delims=" %%e IN ("%filename1%") DO (
SET "line=%%e"
FOR /f "tokens=3 delims=|" %%y IN ("!line:||=|(missing)|!") DO ECHO %%y
)
)>"%outfile%"
TYPE "%outfile%"
GOTO :EOF
Always verify against a test directory before applying to real data.在应用于真实数据之前,请始终对照测试目录进行验证。
Note that if the filename does not contain separators like spaces, then both usebackq
and the quotes around %filename1%
can be omitted.请注意,如果文件名不包含空格等分隔符,则可以省略
usebackq
和%filename1%
周围的引号。
The magic is that for each line, ||
神奇的是对于每一行,
||
is replaced by |(missing)|
被
|(missing)|
取代. .
This simple solution has its faults - for instance if there is |||
这个简单的解决方案有其缺点 - 例如如果有
|||
in the source data, or the usual suspects (some punctuation symbols like !
) but should be quite happy with alphameric source text.在源数据中,或者通常的嫌疑人(一些标点符号,如
!
),但应该对字母数字源文本非常满意。
Another way would be to use a third-party utility like sed
to pre-process the source data.另一种方法是使用像
sed
这样的第三方实用程序来预处理源数据。
The fundamental reason for this phenomenon is that for/f
parses the line as [delimiters]token1[delimiters]token2...
, where [delimiters]
is any sequence of any of the delimiter characters.这种现象的根本原因是
for/f
将行解析为[delimiters]token1[delimiters]token2...
,其中[delimiters]
是任何定界字符的任意序列。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.