Solved

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

Posted on 2013-05-20
7
351 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
[X]
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
7 Comments
 
LVL 85

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 55

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
How Do You Stack Up Against Your Peers?

With today’s modern enterprise so dependent on digital infrastructures, the impact of major incidents has increased dramatically. Grab the report now to gain insight into how your organization ranks against your peers and learn best-in-class strategies to resolve incidents.

 
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

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

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…
AutoHotkey is an excellent, free, open source programming/scripting language for Windows. It started out as a keyboard/mouse macros product, but has expanded into a robust language. This article provides an introduction to it, with links to addition…
There are cases when e.g. an IT administrator wants to have full access and view into selected mailboxes on Exchange server, directly from his own email account in Outlook or Outlook Web Access. This proves useful when for example administrator want…
There's a multitude of different network monitoring solutions out there, and you're probably wondering what makes NetCrunch so special. It's completely agentless, but does let you create an agent, if you desire. It offers powerful scalability …

705 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