Page 1 of 1

Loop and append different string to each file?

Posted: 25 Aug 2020 05:47
by Shohreh
Hello,

I'd like your input on how to solve this problem.

I need to write a loop to 1) read all TXT files in a directory, and 2) insert a different string in each file.

Pseudo-code:

Code: Select all

for %%f in (*.TXT) DO (
ECHO Handling %%f
SELECT CASE
	CASE 1.TXT:
		echo "some text" >> %%f
	CASE 2.TXT:
		echo "some other text" >> %%f
	CASE 3.TXT:
		echo "yet some other text" >> %%f
)
Can cmd do this, ideally for Windows 7/8/10?

Thank you.

Re: Loop and append different string to each file?

Posted: 25 Aug 2020 07:48
by Squashman

Code: Select all

for %%G in (*.TXT) DO (
ECHO Handling %%G
IF "%%G"=="1.TXT" echo "some text" >> %%G
IF "%%G"=="2.TXT" echo "some other text" >> %%G
IF "%%G"=="3.TXT" echo "some more text" >> %%G
)

Re: Loop and append different string to each file?

Posted: 25 Aug 2020 07:55
by Shohreh
Simple enough :-)

Still, would it be possible to use a second loop, since I won't know the names of the input files? I only used 1.txt 2.txt as examples.

Code: Select all

@echo off 

if "%~1"=="" GOTO PARAM

setlocal enableextensions enabledelayedexpansion

set items[0]="Some text"
set items[1]="Some other text"
set items[2]="Yet some other text"

set COUNTER=0
for %%f in ("%1") DO (
	echo Handling file %%f

	REM OK echo !COUNTER!
	
	REM BAD echo !items[!COUNTER!]! 
	REM BAD echo !items[%%COUNTER]! 
	
	REM COUNTER not incremented → always shows first item
	echo !items[%COUNTER%]! 

	set /a COUNTER +=1
)
GOTO END

:PARAM
echo Usage : %0 *.txt OR %0 file1.txt file2.txt

:END
echo Done