[英]How to extract a string from the first line of a file using batch?
I have these files that contain a name in the first line I wish to extract. 我有这些文件,这些文件的第一行要提取一个名称。 All the methods I have approach either result in error or give me nothing. 我所采用的所有方法要么导致错误,要么什么都不给我。
An example file can be found here: https://www.dropbox.com/s/0kcgj8vr3wii33s/FORS2.2011-10-23T23_59_20.355_out.fits?dl=0 可以在此处找到示例文件: https : //www.dropbox.com/s/0kcgj8vr3wii33s/FORS2.2011-10-23T23_59_20.355_out.fits?dl=0
I wish to extract "PN-G013.3+01.1", which lies on the first line (column 2091 in this case, the name is unique to each file) and is classed as "OBJECT". 我希望提取“ PN-G013.3 + 01.1”,它位于第一行(在这种情况下,列2091,名称对于每个文件都是唯一的),并且被分类为“对象”。
Thank you in advance! 先感谢您!
Peter 彼得
Interesting problem! 有趣的问题! Long lines may be read via chunks of 1023 characters long using set /P
command; 使用set /P
命令可以通过1023个字符长的块读取长行; this method works as long as the line be less than 8193 characters long. 只要该行的长度少于8193个字符,此方法就可以使用。 This method also allows you to search for any string in the whole file, not just in the first line, and does not require any hard-coded lenghts. 此方法还允许您搜索整个文件中的任何字符串,而不仅是在第一行中,并且不需要任何硬编码的长度。
@echo off
setlocal EnableDelayedExpansion
set "file=FORS2.2011-10-23T23_59_20.355_out.fits"
call :ReadLongLine < "%file%"
goto :EOF
:ReadLongLine
set "line="
:nextPart
set "part="
set /P part=
set "line=!line!!part!"
if "!part:~1022!" neq "" goto nextPart
set "line=!line:*OBJECT=!"
for /F "tokens=2 delims='" %%a in ("!line:~0,80!") do set "result=%%a"
echo Result: "%result%"
I suspect you have problems with it because it has Unix line endings instead of DOS style line endings. 我怀疑您对此有问题,因为它具有Unix行尾而不是DOS样式行尾。
This appears to work, but it's a bit brittle - tied to the position of the contents of the example you linked: 这似乎可行,但是有点脆弱-与您链接的示例内容的位置有关:
for /f "usebackq delims== tokens=28" %%a in (`findstr /n "OBJECT" FORS2.2011-10-23T23_59_20.355_out.fits`) do (
set x=%%a
)
set x=%x:'=%
for /f "tokens=1" %%a in ("%x%") do (set x=%%a)
echo %x%
If it's always a 14 character name field, you can skip the last for loop and try: 如果它始终是一个14个字符的名称字段,则可以跳过最后一个for循环并尝试:
for /f "usebackq delims== tokens=28" %%a in (`findstr /n "OBJECT" FORS2.2011-10-23T23_59_20.355_out.fits`) do (
set x=%%a
)
set x=%x:~2,14%
echo %x%
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.