Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove all white spaces from a given text file

Tags:

linux

bash

sed

I want to remove all the white spaces from a given text file. Is there any shell command available for this ? Or, how to use sed for this purpose.

I want something like below:

$ cat hello.txt | sed ....

I tried this : cat hello.txt | sed 's/ //g' .But it removes only spaces, not tabs.

like image 503
Lunar Mushrooms Avatar asked Mar 31 '12 06:03

Lunar Mushrooms


People also ask

How do I remove blank spaces in a text file?

The easy way would be select everything (Ctrl+A), go to Edit>Blank Operation>Trim Trailing Space. This should remove all the spaces in between.

Which function is used to remove all blank spaces?

The TRIM function is fully automatic. It removes removes both leading and trailing spaces from text, and also "normalizes" multiple spaces between words to one space character only.


2 Answers

$ man tr NAME     tr - translate or delete characters  SYNOPSIS     tr [OPTION]... SET1 [SET2]  DESCRIPTION    Translate, squeeze, and/or delete characters from standard     input, writing to standard output. 

In order to wipe all whitespace including newlines you can try:

cat file.txt | tr -d " \t\n\r"  

You can also use the character classes defined by tr (credits to htompkins comment):

cat file.txt | tr -d "[:space:]" 

For example, in order to wipe just horizontal white space:

cat file.txt | tr -d "[:blank:]" 
like image 73
Paulo Scardine Avatar answered Oct 02 '22 04:10

Paulo Scardine


Much simpler to my opinion:

sed -r 's/\s+//g' filename 
like image 36
Lucie G Avatar answered Oct 02 '22 03:10

Lucie G