user3581307
user3581307

Reputation: 23

Windows: How to append text at a particular location in a file

I need to append the password to a file(I have password stored in another file). So basically I will be looping thru the file and checking for the field SYS_PASSWD= I need to append the password to this field. Is there a way to do it using dos script? What option should I use? An example will help. Thanks

Upvotes: 0

Views: 70

Answers (1)

Magoo
Magoo

Reputation: 79957

@ECHO OFF
SETLOCAL
:: Get password from file "q24730439.txt"
FOR /f "delims=" %%a IN (q24730439.txt) DO SET "syspasswd=%%a"

:: insert password into appropriate place in "24730439q.txt"
:: creating newfile.txt
(
FOR /f "delims=" %%a IN (24730439q.txt) DO (
  IF "%%a"=="SYS_PASSWD=" (ECHO %%a%syspasswd%) ELSE (ECHO %%a)
)
)>newfile.txt

GOTO :EOF

This procedure appends the password in q24730439.txt to the line SYS_PASSWD= in 24730439q.txt, producing newfile.txt


"delims=" turns off delimiters by setting the delimter character set to empty. Consequently, the entire line is assigned to the metavariable %%a

You stated simply have password stored in another file - the setting of the variable in the manner indicated will read the password from the file q24730439.txt. You have given no other indication of how to derive the password, and I can't read your mind.

It is normal practice to create new files so the solution can be debugged. In the same way, a delete or rename would normally simply be echoed rather than being executed so that no damage can occur if the developer 's system and OP's system differ. All that needs to be done would be to remove the echo to activate the rename/deletion - but that step is last, after the verification that the correct instruction sequence will be generated.

In your case, creating a new file allows

fc newfile.txt 24730439q.txt

to be executed to see the differences.

Once you've verified that the results are correct, a simple

move /y newfile.txt 24730439q.txt >nul 2>nul

overwrites the old file with the new. This command can be inserted before the goto :eof - but only after correct operation of the procedure has been verified.

Upvotes: 1

Related Questions