Home > Enterprise >  how to write batch script on command prompt to extract nth line from multiple txt files?
how to write batch script on command prompt to extract nth line from multiple txt files?

Time:11-16

What's the batch script I should write on Windows command prompt to extract the values from 20th line of 200 text files and put them into a new text file named "master.txt"

Each text files contains hundreds of lines, and I only need the value from line 20.

For example

text file name:

test1.edit.txt

test2.edit.txt

test3.edit.txt

......

Sample File:

Line 1 - xxxxx

Line 2 - xxxxx ......

Line 20- PROPERTY 100

Result:

PROPERTY 100 (from test1.edit.txt)

PROPERTY 200 (from test2.edit.txt)

PROPERTY 300 (from test3.edit.txt) ......

Thank you in advance

CodePudding user response:

If you have cigwin installed, write a,simple bash script that looks like:

for f in `ls f?`; do
   head -9 $f | tail -1
done

change the "f?" to find whatever your file names are (mine are f1, f2, f3). Save the script as "line9" and run it as bash line9

If you don't have cygwin, consider installing it. :-) It really does have lots of useful unixish tools.

CodePudding user response:

Copy this code to a batch file. Drag the folder where the TXT files are to the batch file. It should save all "line 20" text to a file called "Result.txt"

@echo off

if /i exist "%~1" (if /i not exist "%~1\" exit) else (exit)

set "Folder=%~1"
if /i exist "Result.txt" del /q "Result.txt"

pushd "%Folder%"
for /f "delims=" %%a in ('dir /b *.txt') do Call :GetLine "%%a"

popd
cmd.exe /c start "" notepad Result.txt
exit

:GetLine
for /f "skip=19 eol= delims=" %%a in ('type "%~1"') do (
                                                        echo %%a
                                                        >>%~dp0Result.txt echo %%a
                                                        goto :EOF
                                                       )
goto :EOF

enter image description here

  • Related