0

I know it's a silly google question, but I didn't find something really simple for my need.

I have a .txt file with the following content:

hostname [ip] 
exec /bin/bash

Now, every time when I execute a certain PS script(from RUN) I want that [ip] will be changed according to my $args[0]

For example:

.txt now:

hostname 1.1.1.1 
exec /bin/bash

I am executing from run script 2.2.2.2

.txt expected:

hostname 2.2.2.2
exec /bin/bash

Note! The whole content will be always the same, only [ip] changes.

I am looking for the most simple replace solution, thanks :)

1

Your question is quite broad, and I don't want to write a whole script, so I will just answer the main part of it.

To replace "[ip]" in a file with "1.1.1.1":

gc input_file.txt | % { $_ -replace '\[ip\]', '1.1.1.1' } | sc output_file.txt

If you want to overwrite the original file, you need to put parentheses around the first statement so that it loads the entire file into memory at the beginning:

(gc my_file.txt) | % { $_ -replace '\[ip\]', '1.1.1.1' } | sc my_file.txt

gc is short for Get-Content, sc is Set-Content, and % is ForEach-Object.

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.