Solved

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

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

Expert Comment

by:oBdA
Comment Utility
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
setlocal
set Folder=
set Mask=*.txt
for %%a in ("%Folder%\%Mask%") do call :process "%%a"
goto :eof
:Process
for /f "usebackq delims=" %%a in ("%~1") do 	echo %~nx1	%%a&goto :eof)

Open in new window

0
 
LVL 43

Assisted Solution

by:Steve Knight
Steve Knight earned 375 total points
Comment Utility
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!

Steve
0
 
LVL 51

Expert Comment

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

http://unxutils.sourceforge.net/

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)
Else
   WScript.Echo "No folder specified."
   WScript.Quit
End If

' Make sure it exists
If Not objFSO.FolderExists(strBaseDir) Then
   WScript.Echo "Folder does not exist."
   WScript.Quit
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
      Else
         Wscript.Echo objRead.ReadLine
      End If
   Loop

   ' Close file
   objRead.Close
   Set objRead = Nothing
Next

Open in new window

~bp
0
Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 11

Assisted Solution

by:paultomasi
paultomasi earned 125 total points
Comment Utility
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.

Examples:
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.

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

Accepted Solution

by:
Steve Knight earned 375 total points
Comment Utility
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,

steve
0
 
LVL 11

Expert Comment

by:paultomasi
Comment Utility
dragon-it

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.
0
 
LVL 43

Assisted Solution

by:Steve Knight
Steve Knight earned 375 total points
Comment Utility
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
popd
exit /b

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

Open in new window

0

Featured Post

What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

Join & Write a Comment

If like me you are one who spends a lot of time working and scripting with cmd.exe, sometimes it is handy to be able to quickly view a calendar for a given month and year. This script will quickly do just that!  Save the code posted below to a .bat …
How to remove superseded packages in windows w60 or w61 installation media (.wim) or online system to prevent unnecessary space. w60 means Windows Vista or Windows Server 2008. w61 means Windows 7 or Windows Server 2008 R2. There are various …
Internet Business Fax to Email Made Easy - With eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, fr…
In this tutorial you'll learn about bandwidth monitoring with flows and packet sniffing with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're interested in additional methods for monitoring bandwidt…

763 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

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now