Batch Script – How to Modifying an Array

In this article, we are going to learn how we can modify any array using Batch Script.

We can modify any array in two ways. We can add elements in any array or we can replace elements of any array.

Modify an array by adding an element.

Code :

@echo off 
set arr[0]=Beginner
set arr[1]=for
set arr[2]=Beginner
::adding an element at the end of array.
set arr[3]=GFG
echo The last element of the array is %arr[3]%
pause

Explanation:

  • We are creating an array with name ‘array’.
  • By using ‘set’ we are creating an array, by specifying the index of every element.
set arr[0]=Beginner
set arr[1]=for
set arr[2]=Beginner
  • Now we will add an element at the end of ‘array’ by using last index of array.
  • In above code our last index will be ‘3’. So we will use below expression.
set arr[3]=GFG
  • Above command will add ‘GFG’ at the end of array ‘arr’.
  • At last we are printing last element of array by using ‘%arr[3]%’ , which will print ‘GFG’ as output as it is last element of our array now.

Output:

Output of above code

Modify an array by replacing its Element :

Code :

@echo off 
set arr[0]=Beginner
set arr[1]=and
set arr[2]=Beginner
::replacing an element in any array.
set arr[1]=for
echo The new element at 1 index is %arr[1]%
pause

Explanation:

  • Now we are creating an array ‘arr’.
  • We want to replace ‘and’ by ‘for’ . So now we will use below expression to replace ‘and’ with ‘for’.
set arr[1]=for
  • We are using index of  ‘and’ in given array for replacing it by ‘for’.
  • Then we are printing element at index 1, just to check whether its replaced or not.
  • At last ‘pause’ is used to hold the screen, so that we can see our output.

Output :

Replacing element of any array


Contact Us