Posted: . At: 11:08 AM. This was 5 years ago. Post ID: 13587
Page permalink. WordPress uses cookies, or tiny pieces of information stored on your computer, to verify who you are. There are cookies for logged in users and for commenters.
These cookies expire two weeks after they are set.


Trim multiple spaces with sed into a normal string.


To trim multiple spaces from a sentence and turn it back into properly readable text, use this sed syntax.

sed 's/ \+/ /g'

This is an example.

echo "Hello,     this sentence    has multiple spaces in it and needs               fixing."
Hello,     this sentence    has multiple spaces in it and needs               fixing.

This is not good, but it can be fixed.

Using our sed syntax, we can address this easily.

echo "Hello,     this sentence    has multiple spaces in it and needs               fixing." | sed 's/ \+/ /g'
Hello, this sentence has multiple spaces in it and needs fixing.

This works perfectly, the \+ operator tells sed to filter out more than one space and remove them, but leave one space between words.

Another example, replacing a part of the text with something else.

$ echo "Hello, this sentence has multiple spaces in it and needs fixing." | sed 's/,/ Mr Editor,/g'
Hello Mr Editor, this sentence has multiple spaces in it and needs fixing.

Convert a comma delimited file to newline delimited using this syntax.

$ echo "Hello, this, sentence, has, multiple, spaces, in, it, and, needs, fixing" | sed s'/, /\n/gi';
Hello
this
sentence
has
multiple
spaces
in
it
and
needs
fixing

Read more here: https://securitronlinux.com/uncategorized/converting-a-comma-delimited-file-to-newline-delimited/.


Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.