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

Posted on 2013-05-20
Medium Priority
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
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
LVL 85

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 1500 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 56

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

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

LVL 11

Assisted Solution

paultomasi earned 500 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 1500 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 1500 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

Enroll in August's Course of the Month

August's CompTIA IT Fundamentals course includes 19 hours of basic computer principle modules and prepares you for the certification exam. It's free for Premium Members, Team Accounts, and Qualified Experts!

Question has a verified solution.

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

When you receive another warning that your shared drive is almost full and you have asked your users to clean out old files again and again, here is a single command that may help. This command will place all the files that have not been used rec…
This article was inspired by a question here at Experts Exchange (http://www.experts-exchange.com/Software/Photos_Graphics/Images_and_Photos/Q_28629170.html). The requirements stated in that question are (1) reduce the file size of a large number of…
NetCrunch network monitor is a highly extensive platform for network monitoring and alert generation. In this video you'll see a live demo of NetCrunch with most notable features explained in a walk-through manner. You'll also get to know the philos…
In this video, Percona Solution Engineer Rick Golba discuss how (and why) you implement high availability in a database environment. To discuss how Percona Consulting can help with your design and architecture needs for your database and infrastr…
Suggested Courses
Course of the Month11 days, 5 hours left to enroll

770 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