string 更改索引 X 处的字符串字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9318021/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Change string char at index X
提问by gdoron is supporting Monica
I'm searched for a long time how to do a simple string manipulation in UNIX
我搜索了很长时间如何在中进行简单的字符串操作 UNIX
I have this string:
我有这个字符串:
theStr='...............'
And I need to change the 5th char to A, How can it be done?
我需要将第 5 个字符更改为 A,怎么办?
In C#
it's done like this theStr[4] = 'A'; // Zero based index.
在C#
它是这样做的theStr[4] = 'A'; // Zero based index.
回答by J?rgen R
You can achieve this with sed
, the stream line editor:
您可以使用sed
流线编辑器实现此目的:
echo $theStr | sed s/./A/5
echo $theStr | sed s/./A/5
First you pipe the output of $theStr to sed, which replaces the fifth character with A.
首先,您将 $theStr 的输出通过管道传送到 sed,后者将第五个字符替换为 A。
回答by Ivaylo Strandjev
回答by vmpstr
I don't know if it's elegant, or which version of bash you need, but
我不知道它是否优雅,或者你需要哪个版本的 bash,但是
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
第一部分返回前四个字符,然后是字符“A”,然后是从第 6 个字符开始的所有字符