[Original]:http://mydebian.blogdns.org/?p=144
How to remove spaces or newline characters from a string.
So, let me-explain-in-Bash a set of words separated by one or more spaces characters is a very common thing Cause it is very easy to split and work with it. Thus, there are very little cases where you could need to remove all the spaces characters.
However, here are a little and simple example the how could your doing that:
$ echo "A b c D" | Sed ' s///g '
ABCD
Simple enough, eh?
If the text to being modified is already stored in a variabile can even use bash parameter substitution:
$ string= "A b C D"
$ echo ${string///}
ABCD
Quite better!
And what if we want to remove newline characters?
The answer unfortunately is not so easy seeing that:
$ ECHO-E "A B c/nd E F" | Sed ' s//n//g '
a b c
d E F
Doesn ' t bring to the desired result. In fact, if we want to remove newline characters a string we need to manually And then remove the wanted element; Here are how we can do it:
$ echo-e "A/NB/NC/ND/NE/NF" | Sed '/^.*$/n;s//n//g '
ab
cd
EF
This isn't yet the final result:only one newline every two is removed.
This is what it works: /^.*$/ matches the strings composed by zero or more of any character (. *) and starting/ Ending with the line/ n Store the matched string to the pattern spaces and get the next s/ substitute /n/ newline character // with nothing /g globally
The final solution for newline characters removal is:
$ echo-e "A/NB/NC/ND/NE/NF" | Sed ': Start/^.*$/n;s//n//g; T start '
Which involves spaghetti code (start is a label and T-start is just a goto).
If the input is a file there is nicer way:
#!/bin/bash result= ""; while read line; Do result= "$result $line"; Done < MyFile
Ps:
Echo-e "A/NB/NC/ND/NE/NF" | Tr-d "/n"
Does the trick also