Reputation: 150313
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
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
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
Reputation: 71009
a="............"
b="${a:0:4}A${a:5}"
echo ${b}
Here is one really good tutorial on string manipulation.
Upvotes: 19