0
votes

I have a batch file that looks in several .RTF files (file1) for specific info then puts the name of the document in file2. I need to create a comma delimited file (file3) to use in a command line email program to send all the file1's as attachments based on the contents of file2.

The batch file I have creates all file1 and file2 correctly. I have a FOR statement that adds a comma to the end of the document names in file2 and it displays the document name with comma when issuing the ECHO command.

The batch file will output only the last document name/comma it encounters to file3.

How can I get all of the document names in file2 to written to file3 with a comma at the end of each line.

Current output to file3:

7868685425587963.rtf,

Desired output to file3:

7868684496427836.RTF,
786868535408221.RTF,
7868685416423800.RTF,
7868685425587963.rtf,

Script in batch file:

setlocal

del file2.txt
del file3.txt

set comma=,
echo %comma%

rename *.DAT *.RTF,

findstr /m "0097" *.RTF >> file2.txt 

for /f  %%a In (file2.txt) DO set str=%%a%comma%  
echo %str%>> file3.txt

pause

endlocal

command line output:
command line output

I've been trying to figure this out off and on for several weeks and have tried many iterations.

2
>> file3.txt (for /f %%a In (file2.txt) DO echo(%%a%comma%)JosefZ
Please copy the text from your cmd window - don't post links to pictures.user6811411

2 Answers

0
votes

Instead of setting str over and over,

for /f  %%a In (file2.txt) DO set str=%%a%comma%  
echo %str%>> file3.txt

directly append to the file.

for /f  %%a In (file2.txt) DO echo %%a%comma%>> file3.txt
0
votes

The problem in your code is that the command echo %str% is outside of the for /F loop, so it executes after the loop and outputs the last line only. LotPings already shows in their answer how to solve that.

However, you do not need to create the interim file file2.txt for your task, the for /F loop can be used to capture the output of the findstr command line:

> "file3.txt" (
    for /F "delims=" %%F in ('
        findstr /M /F:"file1.txt" "0097"
    ') do (
        echo(%%F,
    )
)

If you want to search all .rtf files in the current directory rather than relying on a file file1.txt that lists the .rtf files, use this instead:

> "file3.txt" (
    for /F "delims=" %%F in ('
        findstr /M "0097" "*.rtf"
    ') do (
        echo(%%F,
    )
)