Loop and append different string to each file?

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
Shohreh
Posts: 25
Joined: 26 Feb 2020 08:05

Loop and append different string to each file?

#1 Post by Shohreh » 25 Aug 2020 05:47

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.

Squashman
Expert
Posts: 4194
Joined: 23 Dec 2011 13:59

Re: Loop and append different string to each file?

#2 Post by Squashman » 25 Aug 2020 07:48

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
)

Shohreh
Posts: 25
Joined: 26 Feb 2020 08:05

Re: Loop and append different string to each file?

#3 Post by Shohreh » 25 Aug 2020 07:55

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

Post Reply