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.
String are immutable in Java. You can't change them. You need to create a new string with the character replaced.
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).
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.
a="............" b="${a:0:4}A${a:5}" echo ${b}
Here is one really good tutorial on string manipulation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With