Modifying a character in a string variable

Functions, Variables, String Operators, Command Substitution, Arrays, if/else, while/until, for, case, select, I/O Redirectors, String I/O, Process ID's, Job Control, trap, signals, subshells, debugging.,

Modifying a character in a string variable

Postby G4143 » Fri Mar 12, 2010 11:41 am

Does anyone know how to do this...Can it be done?

I can extract the single characters and print then, I can substitute a string of characters in a string variable while echo'ing it...but I can't find a way to modify a string character by character so that the variable is changed...Does anyone know how to do this? Here's what I have so far...

Code: Select all
#! /bin/sh

echo -n "enter a string->"
read mystr

echo $mystr


strlgth=${#mystr}
cntr="0"

while [ $cntr != $strlgth ]
do   
   echo ${mystr:$cntr:1}
   cntr=`expr $cntr + 1`
done

echo ${mystr/"is"/"are"} #will replace is with are in the echo

echo $mystr #back to original here

exit 0


What I want...

mystr="this is the string"
do something here to change the third character in, say form 'i' to 'g'
so when I echo &mystr it will display 'thgs is the string'

echo $mystr -> will display thgs is the string
G4143
 
Posts: 24
Joined: Tue Mar 02, 2010 9:55 pm
Location: Canada

Re: Modifying a character in a string variable

Postby Watael » Fri Mar 12, 2010 12:50 pm

to change the third character from whatever to 'g'
Code: Select all
mystr="this is the string"
myNewStr="${mystr::2}g${mystr:3}"
echo "$myNewStr"
thgs is the string
Watael
 
Posts: 231
Joined: Mon Mar 02, 2009 3:03 am

Re: Modifying a character in a string variable

Postby G4143 » Fri Mar 12, 2010 3:22 pm

Thanks for the reply Watael, your solution works but looking at it I'm wondering...can I change just the character in the string without having to build and re-save the entire string again like your solution does.
I can explain what I want better in C.

If I have a character - ch[] - array like below.

char ch[] = "this is the string!\n";

now to change the third character I would

ch[2] = 'g';

now the character array is - "thgs is the string!\n"

I guess what I'm after is, can a bash script change something within a variable without having to re-save the entire variable? Hope this makes sense..
G4143
 
Posts: 24
Joined: Tue Mar 02, 2010 9:55 pm
Location: Canada

Re: Modifying a character in a string variable

Postby Watael » Fri Mar 12, 2010 4:02 pm

AFAIK, no.
Watael
 
Posts: 231
Joined: Mon Mar 02, 2009 3:03 am

Re: Modifying a character in a string variable

Postby G4143 » Fri Mar 12, 2010 4:41 pm

Again thank-you for your replies...I couldn't find anything googling so wasn't sure if the functionality existed. It doesn't...Thank-you for the clarification...G4143
G4143
 
Posts: 24
Joined: Tue Mar 02, 2010 9:55 pm
Location: Canada


Return to Programming

Who is online

Users browsing this forum: No registered users and 1 guest