How to remove space or newline characters from a string?

    技术2022-05-19  24

    [原文]:http://mydebian.blogdns.org/?p=144

     

     

    How to remove space or newline characters from a string.

    Well, let me first explain that in Bash a set of words separated by one or more space characters is a very common thing because it is very easy to split and work with it. Thus, there are very little cases where you could need to remove all the space characters.

    However, here is a little and simple example of how could you do that:

    $ echo "a b c d" | sed 's/ //g' abcd

    Simple enough, eh?

    If the text to be modified is already stored in a variabile you 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 that 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 from a string we need to manually place each line into the pattern space and then remove the wanted element; here is how we can do it:

    $ echo -e "a/nb/nc/nd/ne/nf" | sed '/^.*$/N;s//n//g' ab cd ef

    This is not yet the final result: only one newline every two is removed.Here is how it works:

    /^.*$/ matches all the strings composed by zero or more of any character (.*) and starting/ending with the line/N store the matched string to the pattern space and get the nexts/ 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

     


    最新回复(0)