简体   繁体   中英

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

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".

Thank you in advance!

Peter

Interesting problem! Long lines may be read via chunks of 1023 characters long using set /P command; this method works as long as the line be less than 8193 characters long. 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.

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:

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%

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM