0

I used the following code, but set Content is blank in my case. Please help. Thanks.

  set content=

    for /f "delims=" %%i in (fileA.txt) do set content=%%i

    for /f "delims=" %%i in (FileA.txt) do set content=%content% %%i

    ECHO %content%> result.txt


   FileA.txt
      test
      A
      Testing
      B


   Expected Output:
       test A
       Testing B
Radhika Kandasamy
  • 161
  • 1
  • 3
  • 12

3 Answers3

0

Your two for work independently (the second starts when the first is finished).
Your first loop gets the last line of the file and then the second adds every line of the textfile to the variable (there is a limit for variable length and you will soon reach it with this method).
The empty variable at the end is due to lack of using delayed expansion.

Work with a single for and an alternating flag instead:

@echo off 
setlocal enabledelayedexpansion
set flag=0
(for /f "delims=" %%i in (FileA.txt) do (
  if !flag!==0 (
    <nul set /p ".=%%i "
  ) else (
    echo %%i
  )
  set /a "flag=(flag+1) %% 2" 
))>result.txt

Note: due to batch/cmd limitations, this may have some problems (line length, special characters

Stephan
  • 53,940
  • 10
  • 58
  • 91
0

We need '@echo off' statement to not to print code on every execution of the program and only echo statements, 'rem' is to mention the line is a comment. 'SETLOCAL EnableExtensions EnableDelayedExpansion' is need to enable ! statements to resolve the variables.

@echo off

rem this for loop reads the file FileA.txt line by line by specifying delims= (nothing) 
rem then checks the condition if the line is even line or not, if odd then adding it to myVar variable
rem if even then printing both earlier odd with the current even line to the result.txt file.
set myVar=
set nummod2=0
set /a i=0
rem creating an empty file on everytime the program runs
copy /y nul result.txt
SETLOCAL EnableExtensions  EnableDelayedExpansion

for /f "delims=" %%a in (FileA.txt) do (
set /a i=i+1
set /a nummod2=i%%2
if !nummod2!==0 (
echo !myVar! %%a
) else (
set myVar=%%a
)

) >> result.txt;

echo 'Done with program execution. Result saved to result.txt in the same folder of this batchfile'
rem pause
vijay
  • 609
  • 5
  • 9
0

You need a single for command to process all lines and this simple logic: if it is the first line read, store it; else show the stored first line and the second one AND delete the first line, so the same logic be used in all line pairs:

@echo off
setlocal EnableDelayedExpansion

set "firstLine="
(for /F "delims=" %%a in (FileA.txt) do (
   if not defined firstLine (
      set "firstLine=%%a"
   ) else (
      echo !firstLine! %%a
      set "firstLine="
   )
)) > result.txt
Aacini
  • 65,180
  • 12
  • 72
  • 108