0

i have a file like this :

192.168.123 hostname1
192.168.126 hostname2
192.168.125 hostname3
192.168.124 hostname4

And I want to search for a string via CMD ex. hostname2 and add a line after it so it will look like this:

192.168.123 hostname1
192.168.126 hostname2
192.168.128 hostname5
192.168.125 hostname3
192.168.124 hostname4

also it all have to be done in orginal file not moved to another

4
  • 1
    What have you tried? Why do you need to do it in CMD? Commented Jan 16, 2019 at 9:38
  • i tried adding it by echo > file but it adds it and the bottom of the file and yes i have to do it via CMD Commented Jan 16, 2019 at 10:07
  • for /F "tokens=1,2" %%a in (input.txt) do ( NL echo %%a %%b NL if "%%b" equ "hostname2" echo 192.168.128 hostname5 NL ) Commented Jan 16, 2019 at 12:45
  • Note that AFAIK, batch-file cannot read and write to the same file, at the same time. Commented Jan 16, 2019 at 13:08

1 Answer 1

1
@echo off
setlocal

set "string=hostname2"
set "insert=192.168.128 hostname5"

for /f "tokens=1-2 delims= " %%A in (file.txt) do (
    echo %%A %%B
    if /i "%%~B" == "%find%" echo %insert%
) >> file.tmp

move /y file.tmp file.txt

The variable string is the string to find. The variable insert is the new line to insert after the line which matches the value of string.

The for loop delimits each read line by space into 2 tokens. The 1st token will be the IP address (which seems missing an octate).

If value of string is found in the 2nd token at current line being read, then the insert line is inserted.

When done writing to file.tmp, the file replaces file.txt.

Sign up to request clarification or add additional context in comments.

Comments

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.