[How To] Remove Blank Spaces From A File In Unix

[Unix] Remove Blank Spaces From A File

As highlighted in many of my previous posts, sed and awk are mini-programming languages in themselves. One can never learn too much but can only wonder at the vastness of the applications of these utilities.
Wish to remove blank spaces in text file ?? sed at your rescue in what follows :)

Suppose you have a file myfile.txt with the below text.

$ more myfile.txt
MXGWGF678
 7689 MHGSTTW 78790
           JHKHYWT 90192 GZQPOI GTARQ   
  HHYWTSH HBSHJSD JKDDD 777HGJKSDJ         HSGD886GJHT
GHA     HGASJHA   HSLAH :DHWSH


And you wish to remove all the blank spaces in the file and store the results in results.txt file.

$ sed 's/[ ]//g' myfile.txt > results.txt

The result is as follows

$ more results.txt
MXGWGF678
7689MHGSTTW78790
JHKHYWT90192GZQPOIGTARQ
HHYWTSHHBSHJSDJKDDD777HGJKSDJHSGD886GJHT
GHAHGASJHAHSLAH:DHWSH


:: Explanation of the command ::
The forward slashes are delimiters in the sed command.
The s in the begenning stands for substitute.
The square brackest enclose the blank space and the g at the end stands for Global, meaning - search for blank space globally in the file and replace all occurances wih null character, without a space.


To remove blank lines from a text file, click on this link to read the tutorial.

Job accomplished !!