Open In App

Batch Script – Align Right

Last Updated : 19 Dec, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

We can use Batch scripting for manipulating the data. We have certain commands and filters to manipulate and edit certain pieces of data very easily for better visualization. Align Right in Batch scripting is one of the commands/filters that helps in aligning or arranging text in a desired manner. Using this command we can trim, rearrange, align the text which might not be in a position or structure to be readable, and hence it can enhance the readability of the script output.  

Align Right

Align right or the “:~” option is a special filter for a variable in Batch scripting that allows displaying only a certain number of characters from the right. Let’s say you have a variable x with a value of “40004” and another variable y with a value of  ”   404″, there is some whitespace before the second variable. This looks like a small issue but it drastically hinders readability when rendering a data set or data dealing with columns and rows. Align Right or Left is a filter applied to this variable like ~4 to remove the leading 4 characters which here are whitespace for better alignment of the data.

Usage

Let’s see how we can do that using a script to filter out text from a variable. 

We will use the same example as discussed in the above section. TO use the right align operation on variables, we use the command:~number, where the number is an integer.  

@echo off
set x=40004   
set y=   404

echo Before
echo X = %x%
echo Y = %y%
echo:

echo After
echo X = %x%
echo Y = %y:~3%

The above script uses the align filter which truncates the y variable to the left by three characters. Thus the white spaces in the y variable are all removed and only the string value is displayed in the command. 

Let’s see the below example, where we use negative numbers or indexes to align to the right.

@echo off
set x=40004
set y=   404

echo Before
echo X = %x%
echo Y = %y%
echo:

echo After
echo X = %x:~-3%
echo Y = %y:~-3%

In the example above, the x variable is truncated and only the last 3 characters are displayed. The y variable on the other hand has nothing different from the previous example, as we are again displaying the last three characters but it is indeed a different process to extract characters from the end.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads