使用批处理合并文本文件中的行

Combine lines in text file using batch

我想制作一个程序,将文本文件第二行的内容放在第一行。 (第二个没被编辑也没关系)

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

我有两个问题似乎无法解决。

一:循环仅包含变量中每行的第一个单词。

二:Echo 不会用给定的变量替换文件的第一行,而是写入停用的 ECHO 命令(我有 Windows10 的法语版本,只是翻译了文件中写入的内容, 英文 Windows 版本的文字可能略有不同,但你明白了)

如果有什么建议,请解释一下你提供的代码是做什么的(我一直很喜欢学习)

FOR 命令默认使用 space 作为分隔符。所以你必须告诉它不要对 DELIMS 选项使用任何定界符。此外,您应该能够使用单个 FOR /F 命令执行此操作。只需将上一行保存在变量中。

@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

编辑:我想我完全误解了你的问题。一旦您澄清了您的问题,我将在需要时重新发布代码解决方案。

用skip省略第一行,把第二行写两遍。通常,对文件的编辑意味着重写一个新文件并可能重命名以保留旧文件名。

:: Q:\Test18\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

在 运行 之后,初始编号为 1..5 的批处理 a file1.txt 如下所示:

> type file1.txt
2
2
3
4
5

你的问题不是很清楚,可以有几种不同的理解方式。总之,没有for命令,这样管理更简单:

@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