LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   sed, replacing underscore with whitespace (http://www.linuxquestions.org/questions/programming-9/sed-replacing-underscore-with-whitespace-595967/)

fjkum 10-30-2007 11:52 PM

sed, replacing underscore with whitespace
 
hi, I am currently writting a bash script to replace a string with underscore '_' to a whitespace ' '.

How can I use sed to achieve that?

Below is my snippet of my script:

LONG_STRING_WITH_UNDERSCORE = "This_is_my_script"
LONG_STRING_WITH_WHITESPACE = `cat $LONG_STRING_WITH_UNDERSCORE | sed -e 's,_, ,g'`

echo $LONG_STRING_WITH_WHITESPACE

Is this the correct way?


FJ

ghostdog74 10-31-2007 12:10 AM

run the script and find out!
if there are errors, it means not correct, right?

hint: use echo instead of cat and see how it goes

fjkum 10-31-2007 12:28 AM

Quote:

Originally Posted by ghostdog74 (Post 2942986)
run the script and find out!
if there are errors, it means not correct, right?

hint: use echo instead of cat and see how it goes


Ran it and it gives me
"cat: This_is_my_script: No such file or directory."

What's wrong?

angrybanana 10-31-2007 01:09 AM

Code:

LONG_STRING_WITH_UNDERSCORE="This_is_my_script"
LONG_STRING_WITH_WHITESPACE=`echo $LONG_STRING_WITH_UNDERSCORE | sed -e 's,_, ,g'`

echo $LONG_STRING_WITH_WHITESPACE

Works fine for me. Notice not having whitespace around the "=" and using echo instead of cat.

You could also just use tr since all you're doing is substituting one char for another.
Code:

LONG_STRING_WITH_WHITESPACE=`echo $LONG_STRING_WITH_UNDERSCORE | tr '_' ' '`
#OR
LONG_STRING_WITH_WHITESPACE=$(tr '_' ' ' <<< $LONG_STRING_WITH_UNDERSCORE)

Whatever you find more readable.


All times are GMT -5. The time now is 02:26 AM.