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:
- delete all occurrences of the space character, code
0x20. - delete all horizontal space, including the horizontal tab character, "
\t" - 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.
tr -d ' ' < input.txt > no-spaces.txttr -d '[:blank:]' < input.txt > no-spaces.txttr -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 [[:...:]]:
sed 's/ //g' input.txt > no-spaces.txtsed 's/[[:blank:]]//g' input.txt > no-spaces.txtsed 's/[[:space:]]//g' input.txt > no-spaces.txt
- 12,820
- 5
- 48
- 65
-
1+1, POSIX notation for a blank space is the appropriate way to go. – Avinash Raj Oct 19 '14 at 02:26
-
1Great hint to use tr for this task, works great. Only thing I had to adjust was that tr reads input from stdin, so what worked for me was `tr -d ' ' < input.txt > no-spaces.txt`. – Sky Sep 04 '16 at 18:50
-
@Sky's comment works in my macOS (not tested in Linux). Maybe the answer should be updated? – iplus26 Nov 13 '16 at 08:16
-
Thank a lot @Sky, that's indeed a bad error. I'll fix the three lines with `tr` now. (Do you see it anywhere else?) – Volker Siegel Nov 15 '16 at 23:20
-
Note that even `[:space:]` does *not* strip all unicode spaces. – starbeamrainbowlabs Apr 29 '21 at 21:10
You can use this to remove all whitespaces in file:
sed -i "s/ //g" file
- 5,394
- 2
- 19
- 31
-
3
-
-
1
-
2
-
I use `sed "s: ::g"` when i'm `grep`ing things, what's the difference between the two expression notations? – starscream_disco_party Apr 20 '17 at 01:13
-
1@starscream_disco_party: it‘s the same. You can replace all 3`/` with a different character, e.g.: `sed "ss ssg"` – Cyrus Apr 20 '17 at 05:17
-
You may want to try without the `-i` flag (`--in-place`) first — pipe `|` to `less` for instance. – user598527 Apr 07 '23 at 09:59
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
- 41
- 3