Command or Script to Get First Line of Every File in A directory

Posted on 2013-05-20
Last Modified: 2013-06-04
What is a command or script to get first line of every file in a directory? Help! Thank you!
Question by:syseng007
LVL 84

Expert Comment

ID: 39181401
Try this; it adds the file name and a tab before the actual first line, so that you'll know from which file the respective line comes (to put that into a file, simply redirect the script's output: SomeBatch.cmd >SomeTextFile.txt):
@echo off
set Folder=
set Mask=*.txt
for %%a in ("%Folder%\%Mask%") do call :process "%%a"
goto :eof
for /f "usebackq delims=" %%a in ("%~1") do 	echo %~nx1	%%a&goto :eof)

Open in new window

LVL 43

Assisted Solution

by:Steve Knight
Steve Knight earned 375 total points
ID: 39181422
Hmm, only thing I could come up with on the spot was this:

@echo off
for /f "tokens=*" %%a in ('dir /b /a-d *.txt') do for /f "tokens=*" %%x in ('find /v "" /n "%%~a" ^| find "[1]"') do echo "%%~a","%%~x"

To send to a file:

@echo off
(for /f "tokens=*" %%a in ('dir /b /a-d *.txt') do for /f "tokens=*" %%x in ('find /v "" /n "%%~a" ^| find "[1]"') do echo "%%~a","%%~x") > outputlog.csv

or from commandline:

for /f "tokens=*" %a in ('dir /b /a-d *.txt') do for /f "tokens=*" %x in ('find /v "" /n "%~a" ^| find "[1]"') do echo "%~a","%~x"

That makes a csv file of the form:

"filename.txt","firstl line of the file"

Must be a better way!

LVL 54

Expert Comment

by:Bill Prew
ID: 39183201
If you can use a utility program, get the HEAD command ported to Windows from:

If not, then just to mix it up, here's a VBS approach.  Save as a VBS file and run it passing it a folder name, and capture output with redirection. For example:

cscript EE28133353.vbs "C:\ee\EE28133353" > "c:\temp\output.txt"

' Define needed constants for I/O
Const ForReading = 1
Const ForWriting = 2
Const TriStateUseDefault = -2

' Define constants for files to process and lines to ouput
Const intLines = 2
Const blnHeader = True

' Create file system object
Set objFSO = CreateObject("Scripting.FileSystemObject")

' Get input folder name from command line
If (WScript.Arguments.Count > 0) Then
   strBaseDir = WScript.Arguments(0)
   WScript.Echo "No folder specified."
End If

' Make sure it exists
If Not objFSO.FolderExists(strBaseDir) Then
   WScript.Echo "Folder does not exist."
End If

' Process each matching file
For Each objFile in objFSO.GetFolder(strBaseDir).Files
   ' Open input file
   Set objRead = objFSO.OpenTextFile(objFile.Path, ForReading, False, TriStateUseDefault)

   ' Process first 'n' lines that we want, write to STDOUT
   intCount = intLines
   Do Until objRead.AtEndOfStream Or intCount = 0
      intCount = intCount - 1
      ' Include file name if desired
      If blnHeader Then
         Wscript.Echo "[" & objFile.Name & "]" & objRead.ReadLine
         Wscript.Echo objRead.ReadLine
      End If

   ' Close file
   Set objRead = Nothing

Open in new window

The New “Normal” in Modern Enterprise Operations

DevOps for the modern enterprise offers many benefits — increased agility, productivity, and more, but digital transformation isn’t easy, especially if you’re not addressing the right issues. Register for the webinar to dive into the “new normal” for enterprise modern ops.

LVL 11

Assisted Solution

paultomasi earned 125 total points
ID: 39195983
The proper way to do it is as follows:

@echo off
setlocal enabledelayedexpansion

for %%a in (*.txt) do (
  set /p firstline=<%%a
  echo.%%~nxa: !firstline!

Open in new window

This will display the first line of all the text (.TXT) files in the current folder.

Note: To change the filespec, edit '*.txt' in line 4.

for %%a in (*.txt) do (                process '.TXT' files
for %%a in (*.*) do (                    process all files
for %%a in (*.txt *.csv) do (     process '.TXT' and '.CSV' files

Note: To change how the data is displayed, edit '%%a: !firstline!' in line 5.

echo.%%~nxa: !firstline!       display 'filename: ' and firstline
echo.!firstline!                           display firstline
LVL 43

Accepted Solution

Steve Knight earned 375 total points
ID: 39196132
Paul - nice idea, though I wonder if that reads thw hole file or not?  My suggestion using find of course was pretty inefficient and wasnt really happy with it, odBa's one posted at the same time was the other way I was going to do - have you tried yours and that over large no. of big txt files for instance?  might give it a go and see against some big old text based email folders from pegasus or eudora etc,

LVL 11

Expert Comment

ID: 39196519

nice idea, though I wonder if that reads the whole file or not?
No, it ONLY reads in the first line of files - which is what we want.

have you tried yours...
Yes I have tested my code and it works fine.

My comment above shows the proper method for processing syseng007's files.
LVL 43

Assisted Solution

by:Steve Knight
Steve Knight earned 375 total points
ID: 39197536
Paul - you pick out only so many of my words there, was just asking if you had tested speed wise as wondered if using set /p only read the first line or the whole file, seems does only read first line of file - I know only the first line hit the variable, but didn't know if it would process it all.

Timing wise... aside from my ignorably slow FIND method.... this is scanning through 750Mb of old Eudora conversion MBX text files... each batch method choked on some filenames due to helpful chars like & etc. in the mail folder names... set/p fastest, vbscript no filename issues...  I didn't bother to let the FIND method complete...

12:00:01.09 - Start SET/p
The system cannot find the file specified.
12:00:01.13 - End SET/p
12:00:01.13 - Start VBScript
12:00:01.24 - End VBScript
12:00:01.26 - Start Process sub method...
The system cannot find the file Misc - Marketing.MBX.
12:00:02.68 - End Process sub method

Open in new window

I had to add a few quotes to the routines to deal with spaces and chars in the filenames:

@echo off
setlocal enabledelayedexpansion

pushd "C:\1. DATA\pmail\MAIL\eudora"
echo Scanning through 750Mb of Eudora conversion MBX text files

echo %time% - Start SET/p
(for %%a in (*.mbx) do (
  set /p firstline=<"%%~a"
  echo.%%~nxa: !firstline!
)) > ..\setp.txt
echo %time% - End SET/p

echo %time% - Start VBScript
cscript //nologo ..\firstline.vbs "C:\1. DATA\pmail\MAIL\eudora" > ..\vbscript.txt
echo %time% - End VBScript

echo %time% - Start Process sub method
set Folder=
set Mask=*.mbx
(for %%a in (*.mbx) do call :process "%%a") >..\process.txt

echo %time% - End Process sub method
exit /b

for /f "usebackq delims=" %%a in ("%~1") do 	echo "%~nx1"	"%%~a"&exit /b)

Open in new window


Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

The following is a collection of cases for strange behaviour when using advanced techniques in DOS batch files. You should have some basic experience in batch "programming", as I'm assuming some knowledge and not further explain the basics. For some…
You may have already been in the need to update a whole folder stucture using a script. Robocopy does it well and even provides a list of non-updated files in a log (if asked to). Generally those files that were locked by a user or a process by the …
With Secure Portal Encryption, the recipient is sent a link to their email address directing them to the email laundry delivery page. From there, the recipient will be required to enter a user name and password to enter the page. Once the recipient …
I've attached the XLSM Excel spreadsheet I used in the video and also text files containing the macros used below.…

820 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question