How to get just the first line of a text file written into a new text file using a batch file? - batch-file

Okay I have several lines in a text file. I want to get the first line and save it in another file. For example this is the text file:
put returns between paragraphs
for linebreak add 2 spaces at end
for linebreak add 2 spaces at end2
for linebreak add 2 spaces at end3
I want put returns between paragraphs to be saved into another file.
I used
for /f "tokens=" %%A in ('findstr /r "^[0-9][0-9]*$" <"C:\Users\Sherlock\Desktop\AbcImport\123.txt"') do echo 123>>1234.txt
pause
But it doesn't work at all.
How to get just the first line of a text file written into a new text file using a batch file?

Option 1 - SET /P : This is the simplest and fastest pure batch solution, provided the line does not exceed 1021 bytes, and it does not end with control characters that must be preserved. The size of the file does not matter - it will always read and write the first line very quickly.
#echo off
setlocal enableDelayedExpansion
set "ln="
<"input.txt" set /p "ln="
>"output.txt" (echo(!ln!)
Option 2 - FOR /F : This will work with lines up to ~8191 bytes long, but it can be slow if the file is really large because the FOR /F loop must read the entire file before it processes the first line. This solution is basically the same as the Mofi answer, except it disables the EOL option, so it never ignores the first line, regardless what the first character is. It does have a limitation that it will skip empty lines, so technically it does not give the correct result if the first line is empty:
#echo off
for /f usebackq^ delims^=^ eol^= %%A in ("input.txt") do echo(%%A>"output.txt"&goto :break
:break
There is a way to preserve the first line if it is empty using pure batch, but I would not bother. I would move on to ...
Option 3 - JREPL.BAT, or some other non-batch solution : Batch is quite poor at manipulating text files. You are much better off using some other scripting language like VBScript, JScript, or Powershell. Or a Windows port of any number of unix utilities.
I would use JREPL.BAT - a hybrid JScrpit/batch regular expression text processing utility that runs natively on any Windows machine from XP onward. It is way overkill for such a simple task, but it is an extremely handy, powerful, and efficient tool to have in your arsenal. Once you have it, then it can be used for many text processing tasks. Full documentation is embedded within the script.
jrepl "^.*" "$&" /jendln "quit=true" /f "input.txt" /o "output.txt"
Use CALL JREPL if you put the command within a batch script.

Here is the batch code to write just first non blank/empty line of a text file into another text file.
#echo off
for /F "usebackq delims=" %%I in ("InputTextFile.txt") do (
echo %%I>"OutputTextFile.txt"
goto ContinueAfterLoop
)
:ContinueAfterLoop
InputTextFile.txt is the file in current directory containing the first line to copy.
OutputTextFile.txt is the file created in current directory with first line from input file copied into this output file.
The command GOTO is used to exit the loop after first line is processed and continue the batch file below the loop.
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
echo /?
for /?
goto /?
Read also the Microsoft article about Using Command Redirection Operators.

You can use use this command:
SetLocal EnableDelayedExpansion
for /f "tokens=* delims=;" %%m in ("C:\Users\Sherlock\Desktop\AbcImport\123.txt") do (
set /p FirstLine=<%%m
echo !FirstLine!>>1234.txt
)
and for multiple file:
SetLocal EnableDelayedExpansion
for %%a in ("*") do (
for /f "tokens=* delims=;" %%m in ("%%a") do (
set /p FirstLine=<%%m
echo !FirstLine!>>1234.txt
)
)

rem Get the first line of a text file:
set /P "line=" < "C:\Users\Sherlock\Desktop\AbcImport\123.txt"
rem Write it into a new text file:
echo %line%> 1234.txt

Related

Merge two .txt files in batch in new lines, alternating one from each [duplicate]

This question already has answers here:
Interleave files with CMD using echo
(1 answer)
How can two text files be read in parallel by a batch file?
(1 answer)
Closed 3 years ago.
I want to merge two .txt files following a pattern that uses one line from file1, adds a break and follows with another from file2, then repeat.
I've tried to solve this in notepad++' replace function, but it seems out of its scope completely. I've had mixed success using batch (only useful tool I'm familiar with) managing to make the .bat file past the lines separately with linebreaks, but I can't find information on how to select one line from each file alternating instead of the whole file at once.
This is the .bat file I have so far:
#Echo off
( for /f "delims=" %%A in (
'Type 1.txt^&Echo:^&Type 2.txt'
) Do #Echo:%%A
) > 3.txt
Current output format:
entire file1.txt
entire file2.txt
Intended output format:
single line from file1.txt
single line from file2.txt
repeat
I continue researching but I'm not seeing much that can point me in the right direction, all help appreciated.
Windows command processor cmd.exe interpreting and executing a batch file is not designed for text file processing. It is designed for execution of commands and executables. There are lots of other scripting languages which would be better for this task than cmd.exe.
However, this small batch file works for this task with some limitations.
#echo off
setlocal EnableExtensions EnableDelayedExpansion
set "LineNumber=0"
for /F usebackq^ delims^=^ eol^= %%I in ("file1.txt") do (
set /A LineNumber+=1
set "Line[!LineNumber!]=%%I"
)
set "LineNumber=0"
(for /F usebackq^ delims^=^ eol^= %%I in ("file2.txt") do (
set /A LineNumber+=1
call echo(%%Line[!LineNumber!]%%
echo(%%I
))>"file3.txt"
endlocal
The limitations are:
The number of non-empty lines must be equal in both input files.
The two input files do not contain empty lines which should be also written into output file as empty lines are ignored by FOR.
The lines in both input files do not contain exclamation marks as otherwise those lines are corrupted by enabled delayed expansion on double parsing of the command lines with %%I.
The first input file is not too large to be loaded into memory space for environment variables.
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
call /?
echo /?
endlocal /?
for /?
set /?
setlocal /?
This will do it if the files aren't the same size. The batch file counts the lines in each file and compares the line counts. If one file has more lines than the other, the shorter one will output empty lines for missing lines in file with less lines.
Personally I would go this route then just fix the blank lines with PowerShell if I needed this script for myself.
#echo off
setlocal EnableExtensions DisableDelayedExpansion
pushd "\\server\folder"
set "InputFile1=File1.txt"
set "InputFile2=File2.txt"
set "OutputFile=mix.txt"
(set Newline=^
%==%
)
if not exist "%InputFile1%" goto EndBatch
if not exist "%InputFile2%" goto EndBatch
del "%OutputFile%" 2>nul
for /F "delims=:" %%I in ('%SystemRoot%\System32\findstr.exe /R /N "^" "%InputFile1%"') do set "LineCount1=%%I"
for /F "delims=:" %%I in ('%SystemRoot%\System32\findstr.exe /R /N "^" "%InputFile2%"') do set "LineCount2=%%I"
rem Exchange input file 1 and 2 if input file 2 has more lines than input file 1.
if %LineCount2% GTR %LineCount1% set "InputFile1=%InputFile2%" & set "InputFile2=%InputFile1%"
(
for /F usebackq^ delims^=^ eol^= %%I in ("%InputFile1%") do (
set "LineFile1=%%I"
setlocal EnableDelayedExpansion
set /P LineFile2=
echo(!LineFile1!!Newline!!LineFile2!>>"%OutputFile%"
endlocal
)
)<"%InputFile2%"
:EndBatch
popd
endlocal
pause
Lines starting with a semicolon and containing an exclamation mark are also processed well by this script. Just empty lines in the two input files are ignored and cause unexpected content in output file.
[Mofi] made some edits to this version.
If you wanted to blank the lines with PowerShell like I suggested then save this as clearlines.ps1 and then run it from your batch file at the end.
$pathToFile = "\\server\folder"
(Get-Content -Path $pathToFile) -notmatch '(^[\s,-]*$)| (rows\s*affected)' | Set-Content -Path $pathToFile

Clear whitespace in text file using bat

I have the following batch file HERE
It searches for the line that contains...
[/Script/MyGame.Mode]
Then it creates a new line and adds...
RedirectReferences=(PackageName="%Package%",PackageURLProtocol="%PackageURLProtocol%",PackageURL="%WebAddress%/%Package%%Ext%",PackageChecksum="")
It works unless the original file contains spaces after each line. If there are no spaces it works perfect.
Is there an easy way to clear out all the spaces in the original file before it searches, copies and writes the new line in a new file?
Or is there a better way to do this overall. Sorry but I'm not knowledgeable at batch files yet. Thanks for any help given.
I figured it out. I was able to clear the spaces from the original file with the code below before running the copy and adding the new line.
I changed some file names then ran the code below before I'm checking the file and writing new line.
I had to show some code from my other bat to show you the file name changes. Once you combine everything together in one bat it works fine.
:CLEARWHITESPACE
for /F "eol=; tokens=1 delims=; " %%I in (Game.txt) do (
set /a count+=1
if !count! leq 10 echo %%I>>game.temp.txt
)
:SHOWLINE
set NewURL=RedirectReferences=(PackageName="%Package%",PackageURLProtocol="%PackageURLProtocol%",PackageURL="%WebAddress%/%Package%%Ext%",PackageChecksum="")
pause
:WRITENEW
set inputfile=game.temp.txt
set outputfile=game.temp2.txt
(for /f usebackq^ delims^=^ eol^= %%a in ("%inputfile%") do (
echo %%a
if "%%~a"=="[/Script/MyGame.Mode]" call echo %%NewURL%%
))>>"%outputfile%"

Save specific line from text via batch

So I'm trying to save the contents from the second line of a text file as a variable using Batch. I know there are way better scripting languages to do this with, but batch has command line simplicity that I need. I found this webpage: http://www.netikka.net/tsneti/info/tscmd023.htm But it seems that this method requires an auxiliary program called SED be installed. Are there any methods that do not require SED?
A for loop could work ..
#echo off
Setlocal enabledelayedexpansion
For /f "skip=1 tokens=*" %%a in (myfile.txt) do (
Set secondline=%%a
goto finish
)
: finish
Echo this is my variable !secondline!
Pause

Edit text file using batch file

I've searched a thousand of example and tried, but none of them actually works for me. My requirement is pretty straight forward, I have a file - config.txt, it has one of lines:
sqlServer=localhost
I'm trying to update this line to:
sqlServer=myMachine\sql2012
I looked examples online, some of them are just working with set variables, or some are not replacing but inserting. There are some examples are writing into a new file, but the new file has line number in front of each line. I don't find a useful instruction how to write batch scripts, and none of the update file batch scripts works for me.
It will be very helpful if you leave some comments.
Thanks in advance
EDITED - to adapt to comments
#echo off
setlocal enableextensions disabledelayedexpansion
set "config=.\config.txt"
set "dbServer=localhost\sql2012"
for /f "tokens=*" %%l in ('type "%config%"^&cd.^>"%config%"'
) do for /f "tokens=1 delims== " %%a in ("%%~l"
) do if /i "%%~a"=="sqlServer" (
>>"%config%" echo(sqlServer=%dbServer%
) else (
>>"%config%" echo(%%l
)
type "%config%"
endlocal
Input file is read line by line (for /f %%l), then each line is split (for /f %%a) and if the first token in the line is "sqlserver" then the line is replaced, else the original line is sent to file.
The command used to retrieve the information in the first for loop includes an cd.>"%config%" that will remove the contents of the file, so the final resulting lines (that have been read in memory by the for command before removing them) are sent directly to the same file.
You can do this:
FINDSTR /I /V /B "sqlServer=" config.txt > config.new
ECHO sqlServer=myMachine\sql2012 >> config.new
DEL config.txt
REN config.new config.txt
The FINDSTR will remove all lines that start with sqlServer= and create a new file called newfile.
The ECHO will add a line at the end with sqlServer=MyMachine\sql2012.
The last two lines delete your existing config.txt and replace it with the output of the first two lines.

put contents of a text file in commandline

in a batch I have
echo VirtualDub.video.AddComment^(0x0000000C,"","%tc%"^)^;>>v:\automazioneclip\virtualdubmod\temp\%%~na.vcf
but now in place of %tc% I would like insert the contents of a text file, all content of a text file
How I have to modify it? thanks
Use SET /P to print out the first portion of the line without a newline. Then use TYPE to print out the contents. Then finish up with a normal ECHO.
<nul (
set /p ^"=VirtualDub.video.AddComment^(0x0000000C,"",""
type file.txt
(echo ^"^);)
) >>"v:\automazioneclip\virtualdubmod\temp\%%~na.vcf"
Note that the closing quote after the file contents will appear on the next line if the file ends with a newline. Obviously the value will be spread across multiple lines if the file contains multiple lines. Multiple lines may or may not be a problem depending on the language of the code you are writing.
Related question: How do you loop through each line in a text file using a windows batch file?
So possibly something like:
for /F "tokens=*" %%A in (myfile.txt) do [process] %%A
where "process" is your line above.
for /F "tokens=*" %%A in (myfile.txt) do echo VirtualDub.video.AddComment^(0x0000000C,"","%%A"^)^;>>v:\automazioneclip\virtualdubmod\temp\%%~na.vcf

Resources