batch file to join text

December 14, 2010 at 03:35:44
Specs: Windows XP
Hi, I am trying to create a batch file that reads a text file and if a line of text starts with a '$' then it is added to the previous line (and the original $ line removed). The new lines output to a new file.
i.e.
Oldfile:
my text on a line
$some other text
etc
etc

New file:
my text on a line $some other text
etc
etc

So far I have tried a few combinations such as
::== concat.bat
@echo off
setLocal EnableDelayedExpansion

for /f "tokens=* delims= " %%a in (%1) do (
echo %%a | find "$" > nul
if errorlevel 1 set str1=%%a
if not errorlevel 1 set str2=%%a
echo !str1! !str2! >> %2
)

But I keep getting the original line in the output.


See More: batch file to join text

Report •

#1
December 16, 2010 at 06:38:06
Playing with your code I got this:
================= BATCH CONTENT=======================
@echo off
SETLOCAL EnableDelayedExpansion

for /f "tokens=* delims= " %%a in (%1) do (
echo %%a | find "$" > nul
if "!ERRORLEVEL!" == "1" (
IF "!str1!" == "" (
SET str1=%%a
)ELSE (
ECHO !str1!
SET str1=%%a

)
)ELSE (
IF "!str1!" == "" (
SET str1=%%a
)ELSE (
(SET str1=!str1! %%a)
)
)
)
ECHO !str1!
ENDLOCAL
================END OF BATCH CONTENT=======================
Testing it with a text file containing:
==============TEXT FILE CONTENT=======================
my text on a line
$some other text
$something else
etc
etc
$a third thing
===========END OF TEXT FILE CONTENT====================
The output I got was:
===========OUTPUT====================
my text on a line $some other text $something else
etc
etc $a third thing
===========END OF OUTPUT====================

I have not fully tested it but it could help... and I think the code could be a little more tidy but I hope that it can at least help you out a little.

Good luck


Report •

#2
December 16, 2010 at 07:39:34
One more thing... the find will return 0 with a $ symbol in any part of the line. If you want to check when the symbol is at the beginning of the line only, the you should check the first character of the line instead. It could be done using something like:

SET FIRST_CHARACTER=%%a
SET FIRST_CHARACTER=!FIRST_CHARACTER:~0,1!

IF "!FIRST_CHARACTER!" == "$" ECHO It's a Dollar Symbol!

I hope it will be useful for you.


Report •

#3
December 19, 2010 at 13:06:35
Thanks for the help.
I ended up using sed on a unix server I had access to.
sed -e :a -e '$!N;s/\n=/ /;ta' -e 'P;D' file>newfile
(I converted all the $ in my text to = first because I wasn't sure if the $ would cause trouble)

I did have a few problems at first with the windoze unix conversion of the text file.
I needed to do a dos2unix to strip the LF from every line (windows has CRLF)

I'll give the batch version a try when i get a chance.


Report •
Related Solutions


Ask Question