Solved

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

Posted on 2013-05-20
7
345 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 83

Expert Comment

by:oBdA
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
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
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!

Steve
0
 
LVL 53

Expert Comment

by:Bill Prew
ID: 39183201
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
3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

 
LVL 11

Assisted Solution

by:paultomasi
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.

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
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,

steve
0
 
LVL 11

Expert Comment

by:paultomasi
ID: 39196519
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
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
popd
exit /b

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

Open in new window

0

Featured Post

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

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…
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 …
This Micro Tutorial will give you a basic overview how to record your screen with Microsoft Expression Encoder. This program is still free and open for the public to download. This will be demonstrated using Microsoft Expression Encoder 4.
Windows 10 is mostly good. However the one thing that annoys me is how many clicks you have to do to dial a VPN connection. You have to go to settings from the start menu, (2 clicks), Network and Internet (1 click), Click VPN (another click) then fi…

772 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