我有两个文本文件
file1有以下几行
line1
line2
hello-hai-1
hello-2-hai
3-hai-hello
hello文件2有
line4
line3
hello-hai-5
hello-7-hai
6-hai-hello
hai
hello-4我想要做的是复制file2中同时包含hello和hai的所有行,并将其覆盖到file1中的那些行,即no。行数可能相等,也可能不相等。但是所有hello-hai行在这两个文件中都在一起。
我当前使用的代码是
setlocal enabledelayedexpansion
for /f "tokens=1*delims=:" %%i in ('^<file2 essentials\findstr.exe /n "hello"') do set "#%%i=%%j"
(for /f "delims=" %%i in (file1) do (
set "line=%%i"
if not "!line!"=="!line:hello=!" (
if not "!line!"=="!line:hai=!" (
if not defined flag (
for /f "tokens=1*delims==" %%a in ('set "#"') do echo(%%b
set "flag=true"
)
) else echo !line!
) else echo(!line!
))>output.txt 这会将所有hello行复制到file1中的hello-hai行,我想知道如何将单词hai添加到第一个文件的搜索中
发布于 2013-05-12 02:45:16
@echo off
setlocal EnableDelayedExpansion
rem Find lines with both strings in file2
set i=0
for /F "delims=" %%a in ('findstr "hello" file2 ^| findstr "hai"') do (
set /A i+=1
set "file2[!i!]=%%a"
)
rem Merge file1 with the found lines in file2
set i=0
(for /F "delims=" %%a in (file1) do (
set "line=%%a"
if "!line:hello=!" neq "!line!" (
if "!line:hai=!" neq "!line!" (
set /A i+=1
for %%i in (!i!) do echo !file2[%%i]!
) else (
echo !line!
)
) else (
echo !line!
)
)) > output.txt编辑:添加了新版本
以前的解决方案实现了逐行替换,即使匹配的行在任何文件中都不在一起(文件合并),但要求两个文件中匹配的行数相同。下面的新的更简单的版本按照OP要求的方式工作:
@echo off
setlocal EnableDelayedExpansion
(for /F "delims=" %%a in (file1) do (
set "line=%%a"
if "!line:hello=!" neq "!line!" (
if "!line:hai=!" neq "!line!" (
if not defined flag (
findstr "hello" file2 | findstr "hai"
set flag=true
)
) else (
echo !line!
)
) else (
echo !line!
)
)) > output.txt发布于 2013-05-11 19:33:44
@ECHO OFF
SETLOCAL
SET searching=Y
(
FOR /f "delims=" %%i IN (file1.txt) DO (
ECHO %%i|FIND "hello"|FIND "hai" >NUL
IF ERRORLEVEL 1 (ECHO(%%i) ELSE (
IF DEFINED searching TYPE "file2.txt"|FIND "hello"|FIND "hai"
SET "searching="
)
)
)>output.txt
TYPE output.txt
GOTO :EOF这是一个没有临时文件的版本。它只是从file1中重新生成不包含这两个目标字符串的行。当在同一行中找到这两个字符串时,它会输出file2中包含这两个字符串的所有行。searching标志用于确保file2行只输出一次。
它不会复制空行或以;开头的行。如果需要,可以这样做。
https://stackoverflow.com/questions/16495322
复制相似问题