LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   How to replace space using sed in shell script (https://www.linuxquestions.org/questions/linux-newbie-8/how-to-replace-space-using-sed-in-shell-script-668353/)

Ashok_mittal 09-08-2008 06:48 AM

How to replace space using sed in shell script
 
Hi All,

I want to use sed to replace multiple spaces with single character(say : ).
ex: test.txt

12:Mit 23627 83763 tty message


suppose the file test.txt contains the line as above and i want to replace all spaces with : so that the outcome should be like below:

12:Mit:23627:83763:tty:message

i have used

sed 's/ /:/g' test.txt

but this command replacing every single space with a :, so the output is like:

12:Mit:::23627:83763::::tty:::::::message

colucix 09-08-2008 06:57 AM

Use the + modifer to match one or more occurences of the previous regular expression. It needs to be escaped:
Code:

$ echo "12:Mit    23627  83763  tty message" | sed 's/ \+/:/g'
12:Mit:23627:83763:tty:message


jschiwal 09-08-2008 07:05 AM

You could use tr instead:
Code:

tr -s ' ' ':' <inputfile >outputfile


All times are GMT -5. The time now is 07:30 AM.