Top of one file to the top of another

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
john924xps
Posts: 65
Joined: 08 Jun 2012 07:48

Top of one file to the top of another

#1 Post by john924xps » 27 Oct 2012 09:56

Yeah... I've got two files, and I want to be able to just run a batch file in order to transfer the first line of file A to the top of file B, then deleting that line from file A... I'm clear on how to retrieve text from a file, but I'm not sure how to transfer it to the TOP of another file, as well as deleting that relative line in file A.

And how do you copy the last line of a particular file into a variable without using the <file.txt function repeatedly? Are for loops a must in such a situation? Thanks.

foxidrive
Expert
Posts: 6031
Joined: 10 Feb 2012 02:20

Re: Top of one file to the top of another

#2 Post by foxidrive » 27 Oct 2012 10:02

Use set /p to get line one into a variable.

echo the variable into a new temp file.
TYPE fileB >> newtempfile.
move /y newtempfile fileB


and removing the line from fileA:
find /v "%variable%" <fileA >tempfile
move /y tempfile fileA


To get the last line, use a for in do and set an environment variable to the metavariable. The last line will be in the envar when the forindo completes.

dbenham
Expert
Posts: 2461
Joined: 12 Feb 2011 21:02
Location: United States (east coast)

Re: Top of one file to the top of another

#3 Post by dbenham » 27 Oct 2012 13:57

Reading every line with a FOR loop to get the last line is inefficient, and potentially unacceptably slow for a large file.

FIND /C can be used to quickly count the number of lines and then the FOR /F SKIP option can be used to quickly read the last line.

Code: Select all

@echo off
set "file=test.txt"
for /f %%N in ('type "%file%"^|find /c /v ""') do set /a skip=%%N-1
if %skip% leq 0 (set "skip=") else set "skip=skip^=%skip%^ "
for /f %skip%usebackq^ delims^=^ eol^= %%A in ("%file%") do set "lastLine=%%A"
set lastLine


Dave Benham

foxidrive
Expert
Posts: 6031
Joined: 10 Feb 2012 02:20

Re: Top of one file to the top of another

#4 Post by foxidrive » 27 Oct 2012 19:55

dbenham wrote:Reading every line with a FOR loop to get the last line is inefficient, and potentially unacceptably slow for a large file.


True, Dave, for large files. For small files and moderate directory lists it doesn't warrant the added complexity, IMO.

Post Reply