1752808 Members
6100 Online
108789 Solutions
New Discussion юеВ

replacing a charecter

 
joseni
Occasional Contributor

replacing a charecter

Hi ,
I have a variable with some value. eg,

TestVar="abcdefg.dat"

Using code i want to replace .dat to .txt
after replacement operation , the value of TestVar should be abcdefg.txt.

Please help me to achieve this
8 REPLIES 8
James R. Ferguson
Acclaimed Contributor

Re: replacing a charecter

Hi:

# echo $TestVar|sed -e 's/\.dat$/\.txt/'

Note that you must escape (backslash) the dot character in order for it to represent a dot and not any character.

The dollar sign ($) character anchors the string to the end of the line for exact matching.

Regards!

...JRF...
Ivan Krastev
Honored Contributor

Re: replacing a charecter

Use awk:

echo abcdefg.dat | awk '{sub(/.dat/,".txt"); print}'
abcdefg.txt


In this case I substituted .dat with .txt

regards,
ivan
James R. Ferguson
Acclaimed Contributor

Re: replacing a charecter

Hi (again):

Oh, and since you want a destructive update of the variable:

# TestVar=$(echo $TestVar|sed -e 's/\.dat$/\.txt/')

Regards!

...JRF...
A. Clay Stephenson
Acclaimed Contributor

Re: replacing a charecter

There are many ways to do this; here is one leveraging awk's gsub function.

TestVar="abcdefg.dat"
NewVar=$(echo "${TestVar}" | awk '{gsub(".dat$",".txt"); print $0}')
echo "NewVar = ${NewVar}"

Note the '$' at the end of the pattern match; this means that .dat will only be matched at the end of the string.
If it ain't broke, I can fix that.
joseni
Occasional Contributor

Re: replacing a charecter

Thanks a lot for your support
James R. Ferguson
Acclaimed Contributor

Re: replacing a charecter

Hi:

Welcome to the ITRC Forum! As a new member, please see:

https://forums1.itrc.hp.com/service/forums/helptips.do?#28

Regards!

...JRF...
blah2blah
Frequent Advisor

Re: replacing a charecter

i can't image no one suggested these:

newvar="$(basename $testvar dat)txt"
or
newvar-"${testvar%dat}txt"
Steve Post
Trusted Contributor

Re: replacing a charecter

Yep. I just love those unassigned points. I can't get enough of them. Good think we what answers are helpful or bad because of those points.

But I like mystery. Did the answer really help? Or will it destroy the computer? The suspense is killing me.


(sigh).

Try the tr command too. tr for transliterate.
I use this to replace hex numbers with stuff I can see.

Of course you can always use vi on a text file. Run :%s/fromtext/totext/g to replace all "fromtext" phrases to "totext" on every occurance. On every line.