user3129569
user3129569

Reputation: 15

Batch - Copy specific text from one file to another

I need some help with the problem below, and being a batch noob I don't know how I can go about doing this:

I have two .txt files, the first one contains:

In the second txt file has the following:

I want to make the batch file search through the names in the second column (nameofsomething1 & beyond) from the first txt file, copy the number before it and replace the numbers in the second .txt from the first for their corresponding names. Second txt file is all muddled up with more information which I don't want to touch, I just need to change the numbers. Thanks for the help

Upvotes: 1

Views: 3541

Answers (2)

foxidrive
foxidrive

Reputation: 41224

Test this on sample files: file1.txt and file2.txt and it rewrites file2.txt

nameofsomething is the term in your lines.

This uses a helper batch file called repl.bat - download from: https://www.dropbox.com/s/qidqwztmetbvklt/repl.bat

Place repl.bat in the same folder as the batch file or in a folder that is on the path.

@echo off
for /f "tokens=1,2 delims=," %%a in ('find "nameofsomething" ^<"file1.txt" ') do (
   type "file2.txt" |repl "^.*(,%%b,.*)" "%%a$1" >file.tmp
   move file.tmp "file2.txt"
)
pause

Upvotes: 0

Magoo
Magoo

Reputation: 79982

@ECHO OFF
SETLOCAL
:: remove variables starting $
FOR  /F "delims==" %%a In ('set $ 2^>Nul') DO SET "%%a="
FOR /f "tokens=1,2delims=," %%a IN (q21478068.txt) DO SET "$%%a=%%b"
(
FOR /f "tokens=1,2*delims=," %%a IN (q214780682.txt) DO (
 SET "replaced="
 FOR  /F "tokens=1*delims=$=" %%r In ('set $') DO IF "%%b"=="%%s" SET replaced=Y&ECHO(%%r,%%b,%%c
 IF NOT DEFINED replaced ECHO(%%a,%%b,%%c
 )
)>newfile.txt
GOTO :EOF

q21478068.txt is your first file, q214780682.txt is your second. newfile.txt created.

Upvotes: 1

Related Questions