gdoron
gdoron

Reputation: 150313

Change string char at index X

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.

Upvotes: 28

Views: 33367

Answers (3)

vmpstr
vmpstr

Reputation: 5211

I don't know if it's elegant, or which version of bash you need, but

theStr="${theStr:0:4}A${theStr:5}"

The first part returns first four characters, then the character 'A', and then all the characters starting with the 6th one

Upvotes: 7

Jørgen R
Jørgen R

Reputation: 10806

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.

Upvotes: 47

Ivaylo Strandjev
Ivaylo Strandjev

Reputation: 71009

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

Here is one really good tutorial on string manipulation.

Upvotes: 19

Related Questions