Solved WindowsXP Bash Script - Edit Value in File/Add Leading Zero

April 20, 2012 at 13:21:28
Specs: Windows XP
Hi all,

i am new to .bat and cmd operations and scripting so i would be very thank-full for assistance from someone more experienced in Windows Batch scripting.

My Problem:
I got a file with the last Part of my IP Address inside, but this number is missing the leading zeros. For further simple copy and paste operations i would need this NUMBER always as a fully 3 digit Number.

This Number can be everything from 0 to 255, e.g:

I thought about a rule for adding zeros, like this:
NUMBER<10 + add 2 leading zero (e.g. 005)
NUMBER between 10 AND 99 + add 1 leading zero (e.g. 055)
NUMBER>99 + do nothing (e.g. 255)

So how do i access this NUMBER from file and how do i implement above rules as batch script?
How to used AND/OR for cmd scripts?

See More: WindowsXP Bash Script - Edit Value in File/Add Leading Zero

Report •

April 21, 2012 at 07:36:47
How to get the numbers from your file requires some info about file structure, i.e. to post a sample of the file. Then assumed the IP value is stored in the environment variable number

set number=00%number%
set number=%number:~-3%

Report •

April 21, 2012 at 11:45:17
Thanks for your answer.

So far i had little succes in getting the last part of my IP Adress out from a file with adding leading zeros, please see below my code.

FOR /F "tokens=4* delims=." %G IN (C:\ip.txt) DO set number=00%G

But how to implement now a correct logic, something like in my first posting.

IF %number<10
SET number=00%number
IF %number between 10 AND 99
SET number=0%number
SET number=%G

Above is only an example because i do not know the correct syntax for a valid bash.
Would be great if someone could help me make this a valid bash script line.

Report •

April 22, 2012 at 02:59:42
✔ Best Answer
If the file holding the IP address has just ONE line the following does the job

@echo off
for /F "tokens=4 delims=." %%G in (C:\ip.txt) do set number=00%%G
set number=%number:~-3%

I strongly suggest the code I posted since your logic leads to cumbersome coding because a number with leading zeros is interpreted as octal and can't any more be compared as its native decimal value.

By the way bash belongs to Unix/Linux while batch is a script composed by Windows commands

Report •

Related Solutions

April 22, 2012 at 06:17:01
Thank you very much!
This really works perfect for me.

Report •

Ask Question