How to remove spaces or newline characters from a string?

Source: Internet
Author: User

[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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.