簡體   English   中英

替換兩個文件的特定行

[英]replace specific lines of two files

好的。 我有兩個文件file1和file2

文件1

line1
helloa
hellob
line2

文件2

line3
helloc
hellod
helloe
line4

我想用file2替換file1中的所有hello行,這些行在一起,有什么想法嗎?

可以使用此語句完成嗎?

for /f "tokens=1,* delims==" %%a in ('find "hello" ^< file2') do set helloa=%%b

預先感謝您的回答

@ECHO OFF
SETLOCAL
SET "inserted=N"
(
FOR /f %%i IN (file1.) DO (
 ECHO %%i|findstr /b /i "hello" >NUL
 IF ERRORLEVEL 1 (ECHO(%%i) ELSE (
  IF DEFINED inserted (
   SET "inserted="
   FINDSTR /b /i "hello" <file2.
  )
 )
)
)>output.txt
GOTO :EOF

inserted的標志設置為任何值。
讀取file1的每一行。
-如果該行未以“ hello”開始,則回聲
-如果該行以“ hello”開始
*如果設置了標志,請清除它並從file2中輸出行。 以“你好”開始
*如果未設置該標志,則不執行任何操作(跳過file1的其余部分。

嘗試這個:

@echo off &setlocal
for /f "tokens=1*delims=:" %%i in ('^<file2.txt findstr /n "hello"') do set "#%%i=%%j"
(for /f "delims=" %%i in (file1.txt) do (
    set "line=%%i"
    setlocal enabledelayedexpansion
    if not "!line!"=="!line:hello=!" (
        endlocal
        if not defined flag (
            for /f "tokens=1*delims==" %%a in ('set "#"') do echo(%%b
            set "flag=true"
        )
    ) else ( 
        echo(!line!
        endlocal
    )
))>output.txt

輸出在output.txt

編輯:改進了有關delayed expansion行為。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM