Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

bash - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...