TheBoxyBear
TheBoxyBear

Reputation: 391

Combine lines in text file using batch

I want to make a program that takes the content of the second line of a text file and puts it on the first. (It doesn't matter if the second doesn't get edited)

for /f "tokens=1" %%t in (file.txt) do set string1=%%t
for /f "tokens=2" %%t in (file.txt) do set string2=%%t
echo %string1%%string2%>file.txt

I have two issues hat I can't seem to be able to fix.

One: the loops only include the first word of each line in the variables.

Two: Echo doesn't replace the first line of the file with the variables given and instead writes ECHO command deactivated (I have the French version of Windows 10 and simply translated what got written in the file, the text in English Windows version might be slightly different, but you get the idea)

If you have any suggestions, I would appreciate if you explain what the code you provide does (I always like to learn)

Upvotes: 1

Views: 1223

Answers (3)

Aacini
Aacini

Reputation: 67216

Your question is not clear and can be understood in several different ways. Anyway, this management is simpler with no for command:

@echo off
setlocal EnableDelayedExpansion

< file.txt (

   rem Takes the content of the first line
   set /P "line1="

   rem Takes the content of the second line and puts it on the first
   set /P "line2="
   echo !line1!!line2!

   rem It doesn't matter if the second line doesn't get edited
   echo !line2!

   rem Copy the rest of lines
   findstr "^"

) > output.txt

move /Y output.txt file.txt

Upvotes: 2

user6811411
user6811411

Reputation:

Use skip to omit the first line and write the 2nd line twice. In general an edit of a file implies a rewrite to a new file and possibly a rename to retain the old file name.

:: Q:\Test\2018\07\25\SO_51508268.cmd
@Echo off
Set "flag="
( for /f "usebackq skip=1 delims=" %%A in ("file1.txt") Do (
    If not defined flag (
      Echo=%%A
      Set flag=true
    )
    Echo=%%A
  )
) >file2.txt
Del file1.txt
Ren file2.txt file1.txt

After running the batch a file1.txt with initially numbered lines 1..5 looks like this:

> type file1.txt
2
2
3
4
5

Upvotes: 0

Squashman
Squashman

Reputation: 14290

The FOR command uses a space as a delimiter by default. So you have to tell it to not use any delimiters with the DELIMS option. Also, you should be able to do this with a single FOR /F command. Just hold the previous line in a variable.

@ECHO OFF
setlocal enabledelayedexpansion

set "line1="
(for /f "delims=" %%G in (file.txt) do (
    IF NOT DEFINED line1 (
        set "line1=%%G"
    ) else (
        echo !line1!%%G
        set "line1="
    )
)
REM If there are an odd amount of lines, line1 will still be defined.
IF DEFINED line1 echo !line1!
)>File2.txt

EDIT: I think I completely misunderstood your question. Once you clarify your question I will repost a code solution if needed.

Upvotes: 0

Related Questions