0

I'm new to batch script, I have a file with a string containing the word "media"(quotes included) and I need to insert another string right before it. I messed around with findstr but couldn't make heads or tails of it.
Edit2:
here's what i did, doesn't seem to work:

@echo off
SETLOCAL=ENABLEDELAYEDEXPANSION 
for /f "delims=," %%a in (f1.txt) do (  
set foo=%%a  
if !foo!=="media" 
set var=!foo:"media"=aa"media"!
echo !foo! >> f2.txt)
9
  • You can only do string substitution with the SET command in a batch-file. Commented Nov 5, 2017 at 22:50
  • but how do i find the word "media", then i can substitute it with my string+"media" Commented Nov 5, 2017 at 22:54
  • 1
    Use a FOR /F command to read the file. Use the SET command to assign the FOR variable to an environmental variable. Then use another SET command to do the string substitution. Commented Nov 5, 2017 at 23:03
  • Edit your question and update it with your code. Then delete your comment Commented Nov 5, 2017 at 23:15
  • Are you saying that the string "media" is on a line by itself? Commented Nov 5, 2017 at 23:39

1 Answer 1

2

You have two options to do this. You can read the file with a FOR /F command or if you are just editing a single line file then you can use the SET /P command.

Here are both of those examples in a single batch file.

@echo off
setlocal enabledelayedexpansion
for /F "delims=" %%G in (sotemp.txt) do (
    set "line=%%G"
    set "foo=!line:"media"=aa"media"!"
    echo !foo!
)

set /p "line="<sotemp.txt
echo %line:"media"=aa"media"%
pause
Sign up to request clarification or add additional context in comments.

4 Comments

i don't know why but none of them seems to work, the first one does nothing and the second just loads the file content in the command prompt, also after fixing my initial code like you told me, the result file have only the first substring in it. P.S something i forgot to mention is the long string consists of a bunch of substrings seperated by a coma, with "media" being one of those substrings, that's why i used "delims=,"
I did test the code with a limited example based on your description and it works on my end. Without seeing an exact representation of your input and output it will make it nearly impossible for me to troubleshoot for you.
input (file1): abcd"galaxy",efghij"bar",klmno"media",pqrst"hero" output (file2): abcd"galaxy",efghij"bar",klmnoaa"media",pqrst"hero"
scratch that, the first option worked perfectly, it was a dumb mistake from my part! thanks a lot man!

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.