Public Group

# Character replacement in shell scripting

This topic is 4038 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I've been trying to figure out how to replace a single character in a string in shell scripting. So far, the only way I was able to figure this out was to use some nasty string concatenation: newtext="${oldtext:0:$count+189}${index:$count:1}${oldtext:$count+190}" This replaces characters in a line (starting with the 190th) with the nth character of an index. "count" counts from left to right in a loop, replace characters in a line of text. This exists within a loop where count iterates through the string which is replacing sequential characters in oldtext. I'm wondering if there's a way to do something equlivalent to: newtext[count+190] = index[count], but lots of google searching reveals nothing. I'm also unsure as to why $count+190 works in the code above, and why$count+191 is not the correct "solution" to this problem. Thanks a ton in advance. I'm not as bad of a programmer as I may seem, I just don't use shell scripting much.

##### Share on other sites
Which shell scripting language are you using?

##### Share on other sites
I'm using bash:

bash-2.03$echo$SHELL
/bin/bash

##### Share on other sites
To do string replacement you should use the sed command and regular expressions, it just makes life easy. In example to replace a single character in a string the following should work to replace the h in hello.

blah="hello"

##### Share on other sites
OK, I forgot that the indexing was indexed 0-based while my results in the text in the text file was 1-based.

Since the regex thing doesn't work, sed is completely out of the question. I need to make this work without a consistent pattern preceeding the first character replacement position.

I'll take a look to see if I can use cut so solve this problem - it actually seems related to my specific issue.

##### Share on other sites
Hello again if you want to replace a single character at a position then this is even easier than before.

Let us pretend that we have the following string...

blah="asdfghjkl"

Let us also pretend that we want to replace the fourth character (the f) with a Z. The following sed expression will do exactly what we want.

echo \$blah | sed 's/./Z/4'

The output will be the following...

asdZghjkl

As a suggestion however, if you are parsing large ammounts of text I would suggest useing perl.

1. 1
Rutin
26
2. 2
3. 3
JoeJ
20
4. 4
5. 5

• 9
• 9
• 9
• 46
• 41
• ### Forum Statistics

• Total Topics
631750
• Total Posts
3002059
×