Replace text in a file using Batch script

July 31, 2018

Yesterday I was working at a client site. It is a Windows server isolated from external internet access and prohibited to install any new software. I got a task in hand to remove all YAML files id to null. For example, the input file temp.yaml looks like this:

something id: 4 something else id: 64 next one id: 231 another one id: 34

and the target file(result.yaml) I want would be like this:

something id: somthing else id: next on id: another one id:

It is a huge file and it would take a long time to remove each id number one by one manually. The only tool accessible on that windows server machine is a CMD command prompt, therefore we could write a simple batch script to get the job done. Create a file called convert.bat with a text editor like this:

@echo off (for /f “tokens=1* delims=:” %%a in (temp.yaml) do ( if “%%b”=="" (echo %%a) else ( echo %%a|find ” id” >null&& echo %%a: ||echo %%a: %%b ) ))>result.yaml

You can replace the text temp.yaml and result.yaml in the script to your target input and output file respectively. Double click to execute the script and you are done!

For those who are not familiar with the Batch script, here is some basic explanation:

@echo off means to get rid of that C:\Download\ prompt

The for loop has some option, where tokens= specify which numbered items to read from each line (default =1) and delims= specify the delimiter character (default = a space). The %%paramater are variables similar to arguments to batch files. The last line export the result to the file I want. It saves a lot of time with this simple script instead of doing manual work :)

Written by Victor Leung who is a keen traveller to see every country in the world, passionate about cutting edge technologies. Follow me on Twitter