1

Edited **
I have a text file called sample.txt which keeps updating. It contains various pathnames:

C:/users/admin/abc
C:/users/admin/xyz
C:/users/admin/jkl
C:/users/admin/mno
...
...

I want to replace "admin" with "admin1" and save that file in sample1.txt
I tried to use this:

y = admin1  
FOR /F "tokens=* delims=/" %%x in (sample.txt) DO ^  
if %%x==admin (%%y > sample1.txt) else (%%x > sample1.txt)

My output should in sample1.txt:

C:/users/admin1/abc
C:/users/admin1/xyz
C:/users/admin1/jkl
C:/users/admin1/mno

1
  • Accept an answer in this question. Commented Oct 6, 2017 at 19:08

2 Answers 2

2

Will this simple batch file do?

@(For /F "Delims=" %%A In ('Find /I "/admin/"^<"sample.txt"'
) Do @Set "_=%%A"&@Call Echo %%_:/admin/=/admin1/%%)>"sample1.txt"

Edit The following may be less susceptible to poison characters in sample.txt

@(For /F "Delims=" %%A In ('Find /I "/admin/"^<"sample.txt"'
) Do @Set "_=%%A"&Call Set/P "_=%%_:/admin/=/admin1/%%"<Nul&Echo()>"sample1.txt"
Sign up to request clarification or add additional context in comments.

2 Comments

Hey I think it works perfectly, but i found a glitch when i try to put the file name as "C:/users/admin/a&c" ..it does not work for this. Can you tell me how i can correct
TBF, my suggestion is to never have any directory or file named using characters which could cause issues, and that is one of those! You could escape the ampersand, &, with a caret, ^, but my recommendation is that all of the paths within sample.txt should be doublequoted, "C:/users/admin/a&c". I have edited my post with an awkward looking workaround which may however suit your purpose better.
1

you can do the following for bash

#!/bin/bash
set -e

declare -a myarray
readarray myarray < file_pathname # Include newline.
readarray -t myarray < file_pathname # Exclude newline.
new_string=admin1

for s in ${myarray[@]}; do
  echo $s;
  echo ${s/admin/$new_string}
done

11 Comments

the text file keeps updating so, everytime the end value "/abc" ,"/xyz" , etc will keep updating. So i will not be able to use that
I don't understand what you mean. It does what you want replaces admin with admin1
yes it will work. but my text file keeps updating and has many such pathnames inside the text file.
My text file can be: C:/users/admin/abc C:/users/admin/xyz C:/users/admin/jkl C:/users/admin/mno C:/users/admin/asd C:/users/admin/asdasd C:/users/admin/jasdasdkl C:/users/admin/asasd
as long as it's separated by newlines it doesn't matter,
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.