Velvet Star Monitor

Standout celebrity highlights with iconic style.

updates

Sed to delete blank spaces

Writer Matthew Barrera

Does anyone know how to use Sed to delete all blank spaces in a text file? I haven been trying to use the "d" delete command to do so, but can't seem to figure it out

3 Answers

What kind of "space"?

To "delete all blank spaces" can mean one of different things:

  1. delete all occurrences of the space character, code 0x20.
  2. delete all horizontal space, including the horizontal tab character, "\t"
  3. delete all whitespace, including newline, "\n" and others

The right tool for the job

If sed it not a requirement for some hidden reason, better use the right tool for the job.

The command tr has the main use in translating (hence the name "tr") a list of characters to a list of other characters. As an corner case, it can translate to the empty list of characters; The option -d (--delete) will delete characters that appear in the list.

The list of characters can make use of character classes in the [:...:] syntax.

  1. tr -d ' ' < input.txt > no-spaces.txt
  2. tr -d '[:blank:]' < input.txt > no-spaces.txt
  3. tr -d '[:space:]' < input.txt > no-spaces.txt

When insisting on sed

With sed, the [:...:] syntax for character classes needs to be combined with the syntax for character sets in regexps, [...], resulting in the somewhat confusing [[:...:]]:

  1. sed 's/ //g' input.txt > no-spaces.txt
  2. sed 's/[[:blank:]]//g' input.txt > no-spaces.txt
  3. sed 's/[[:space:]]//g' input.txt > no-spaces.txt
5

You can use this to remove all whitespaces in file:

 sed -i "s/ //g" file
6

perhaps this way too late, but sed takes regular expression as input. '\s' is the expression of all whitespaces. So sed s/'\s'//g should do the job. cheers

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy