Bash Insert Character at Specific Index in String



Bash Insert Character at Specific Index in String

In Bash scripting, inserting a character at a specific index in a string is useful for various tasks that require precise string manipulation.


Syntax

new_string="${string:0:index}$char${string:index}"

The basic syntax involves using string slicing to construct a new string with the character inserted at the specified index.


Example Bash Insert Character at Specific Index

Let's look at some examples of how to insert a character at a specific index in a string in Bash:

1. Insert Character at Index 5

This script inserts the character 'X' at index 5 in the string stored in the variable str and prints the result.

#!/bin/bash

str="Hello, World!"
index=5
char="X"
new_string="${str:0:index}$char${str:index}"
echo "$new_string"

In this script, the variable str is assigned the value 'Hello, World!', index is assigned the value 5, and char is assigned the value 'X'. The new string is constructed by slicing str up to index, inserting char, and appending the rest of str. The result is stored in new_string and printed.

Insert character at index 5 in Bash

2. Insert Character at Index 0

This script inserts the character 'A' at index 0 in the string stored in the variable str and prints the result.

#!/bin/bash

str="Hello, World!"
index=0
char="A"
new_string="${str:0:index}$char${str:index}"
echo "$new_string"

In this script, the variable str is assigned the value 'Hello, World!', index is assigned the value 0, and char is assigned the value 'A'. The new string is constructed by slicing str up to index, inserting char, and appending the rest of str. The result is stored in new_string and printed.

Insert character at index 0 in Bash

3. Insert Character at User-Specified Index

This script prompts the user to enter a string, an index, and a character, then inserts the character at the specified index in the string and prints the result.

#!/bin/bash

read -p "Enter a string: " str
read -p "Enter the index: " index
read -p "Enter the character to insert: " char
new_string="${str:0:index}$char${str:index}"
echo "The new string is: '$new_string'"

In this script, the user is prompted to enter a string, an index, and a character. The new string is constructed by slicing str up to index, inserting char, and appending the rest of str. The result is stored in new_string and printed.

Insert character at user-specified index in Bash

Conclusion

Inserting a character at a specific index in a string in Bash is a fundamental task for precise string manipulation in shell scripting. Understanding how to insert characters at specific positions can help you manage and manipulate strings effectively in your scripts.