program tip

텍스트 파일에서 첫 번째 줄을 읽는 Windows 배치 명령

radiobox 2020. 10. 13. 07:38
반응형

텍스트 파일에서 첫 번째 줄을 읽는 Windows 배치 명령


Windows 배치 파일을 사용하여 텍스트 파일에서 첫 번째 줄을 어떻게 읽을 수 있습니까? 파일이 크므로 첫 번째 줄만 처리하고 싶습니다.


다음 은 한 줄이 아닌 nGNU head유틸리티 와 같은 파일에서 맨 위 을 인쇄하는 범용 배치 파일 입니다.

@echo off

if [%1] == [] goto usage
if [%2] == [] goto usage

call :print_head %1 %2
goto :eof

REM
REM print_head
REM Prints the first non-blank %1 lines in the file %2.
REM
:print_head
setlocal EnableDelayedExpansion
set /a counter=0

for /f ^"usebackq^ eol^=^

^ delims^=^" %%a in (%2) do (
        if "!counter!"=="%1" goto :eof
        echo %%a
        set /a counter+=1
)

goto :eof

:usage
echo Usage: head.bat COUNT FILENAME

예를 들면 :

Z:\>head 1 "test file.c"
; this is line 1

Z:\>head 3 "test file.c"
; this is line 1
    this is line 2
line 3 right here

현재는 빈 줄을 계산하지 않습니다. 또한 8KB의 배치 파일 행 길이 제한이 적용됩니다.


어? imo 이것은 훨씬 더 간단합니다

  set /p texte=< file.txt  
  echo %texte%

너희들 ...

C:\>findstr /n . c:\boot.ini | findstr ^1:

1:[boot loader]

C:\>findstr /n . c:\boot.ini | findstr ^3:

3:default=multi(0)disk(0)rdisk(0)partition(1)\WINNT

C:\>

이것을 시도해 볼 수 있습니다.

@echo off

for /f %%a in (sample.txt) do (
  echo %%a
  exit /b
)

편집 또는 네 개의 데이터 열이 있고 5 번째 행에서 아래로 내려 가려면 다음을 시도해보십시오.

@echo off

for /f "skip=4 tokens=1-4" %%a in (junkl.txt) do (
  echo %%a %%b %%c %%d
)

텍스트 파일에서 첫 번째 줄을 읽는 Windows 배치 명령에 대한 응답이있는 thetalkingwalnut 덕분에 다음 해결책을 찾았 습니다.

@echo off
for /f "delims=" %%a in ('type sample.txt') do (
echo %%a
exit /b
)

다른 사람들의 대답을 약간 기반으로합니다. 이제 읽을 파일과 결과를 넣을 변수를 지정할 수 있습니다.

@echo off
for /f "delims=" %%x in (%2) do (
set %1=%%x
exit /b
)

이것은 위와 같이 사용할 수 있음을 의미합니다 (getline.bat라고 가정하면)

c:\> dir > test-file
c:\> getline variable test-file
c:\> set variable  
variable= Volume in drive C has no label.

">"를 사용하는 stdout 리디렉션에 유용한 라이너 1 개 :

@for /f %%i in ('type yourfile.txt') do @echo %%i & exit

이 시도

@echo off
setlocal enableextensions enabledelayedexpansion
set firstLine=1
for /f "delims=" %%i in (yourfilename.txt) do (
    if !firstLine!==1 echo %%i
    set firstLine=0
)
endlocal

EXIT /B솔루션 의 문제 는 배치 파일의 일부로 더 현실적으로 내부에있을 때 다음과 같습니다. 이후에 해당 배치 파일 내에서 후속 처리가 없습니다 EXIT /B. 일반적으로 배치에는 하나의 제한된 작업보다 훨씬 많은 것이 있습니다.

그 문제에 대응하려면 :

@echo off & setlocal enableextensions enabledelayedexpansion
set myfile_=C:\_D\TEST\My test file.txt
set FirstLine=
for /f "delims=" %%i in ('type "%myfile_%"') do (
  if not defined FirstLine set FirstLine=%%i)
echo FirstLine=%FirstLine%
endlocal & goto :EOF

(그러나 소위 포이즌 캐릭터는 여전히 문제가 될 것입니다.)

배치 명령으로 특정 행을 얻는 주제에 대해 자세히 알아보십시오.

How do I get the n'th, the first and the last line of a text file?" http://www.netikka.net/tsneti/info/tscmd023.htm

[Added 28-Aug-2012] One can also have:

@echo off & setlocal enableextensions
set myfile_=C:\_D\TEST\My test file.txt
for /f "tokens=* delims=" %%a in (
  'type "%myfile_%"') do (
    set FirstLine=%%a& goto _ExitForLoop)
:_ExitForLoop
echo FirstLine=%FirstLine%
endlocal & goto :EOF

Note, the batch file approaches will be limited to the line limit for the DOS command processor - see What is the command line length limit?.

So if trying to process a file that has any lines more that 8192 characters the script will just skip them as the value can't be held.


Another way

setlocal enabledelayedexpansion
@echo off
for /f "delims=" %%i in (filename.txt) do (
if 1==1 (
set first_line=%%i
echo !first_line!
goto :eof
))

Here is a workaround using powershell:

powershell (Get-Content file.txt)[0]

(You can easily read also a range of lines with powershell (Get-Content file.txt)[0..3])

If you need to set a variable inside a batch script as the first line of file.txt you may use:

for /f "usebackq delims=" %%a in (`powershell ^(Get-Content file.txt^)[0]`) do (set "head=%%a")

To cicle a file (file1.txt, file1[1].txt, file1[2].txt, etc.):

START/WAIT C:\LAERCIO\DELPHI\CICLADOR\dprCiclador.exe C:\LAERCIUM\Ciclavel.txt

rem set/p ciclo=< C:\LAERCIUM\Ciclavel.txt:
set/p ciclo=< C:\LAERCIUM\Ciclavel.txt

rem echo %ciclo%:
echo %ciclo%

And it's running.

참고URL : https://stackoverflow.com/questions/130116/windows-batch-commands-to-read-first-line-from-text-file

반응형