Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change string char at index X

Tags:

I'm searched for a long time how to do a simple string manipulation in UNIX

I have this string:

theStr='...............' 

And I need to change the 5th char to A, How can it be done?

In C# it's done like this theStr[4] = 'A'; // Zero based index.

like image 911
gdoron is supporting Monica Avatar asked Feb 16 '12 19:02

gdoron is supporting Monica


People also ask

How do you change a character in a string?

String are immutable in Java. You can't change them. You need to create a new string with the character replaced.

How do I replace a character at a particular index in Python?

replace() method helps to replace the occurrence of the given old character with the new character or substring. The method contains the parameters like old(a character that you wish to replace), new(a new character you would like to replace with), and count(a number of times you want to replace the character).


2 Answers

You can achieve this with sed, the stream line editor:

echo $theStr | sed s/./A/5

First you pipe the output of $theStr to sed, which replaces the fifth character with A.

like image 199
Jørgen R Avatar answered Nov 07 '22 22:11

Jørgen R


a="............" b="${a:0:4}A${a:5}" echo ${b} 

Here is one really good tutorial on string manipulation.

like image 39
Ivaylo Strandjev Avatar answered Nov 07 '22 22:11

Ivaylo Strandjev