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:

exec /bin/bash

I am executing from run script

.txt expected:

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 :)


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 "":

gc input_file.txt | % { $_ -replace '\[ip\]', '' } | 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\]', '' } | 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.