How to Remove All White Spaces from a Given Text File

Bash - How to remove all white spaces from a given text file?

$ 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:]"

Removing whitespaces in text file

Be a nerd. You can do it in just one line, using classes in java.nio.file package :)

int count = new String(Files.readAllBytes(Paths.get("/tmp/test.txt")), "UTF-8")
.trim().split("\\s+").length;

to count how many words are in the file. Or

String result = new String(Files.readAllBytes(Paths.get("/tmp/test.txt")), "UTF-8")
.trim().replaceAll("\\s+", " ");

to have a single string with content correctly replaced.

Removing all spaces in text file with Python 3.x

Seems like you can't directly edit a python file, so here is my suggestion:

# first get all lines from file
with open('file.txt', 'r') as f:
lines = f.readlines()

# remove spaces
lines = [line.replace(' ', '') for line in lines]

# finally, write lines in the file
with open('file.txt', 'w') as f:
f.writelines(lines)

How can I remove all spaces from file in Notepad++?

To delete all spaces in the file, replace ' +' with '' (quotes only for demonstration, please remove them). You need to have the checkbox "Regular expression" checked.

To remove all spaces and tabs, replace '[ \t]+' with '' (remove quotes).

This works for big files, too, where the solution of @Learner will be tiresome.

Batch: remove all white spaces from a text file?

!line:~1! removes the first character. What you want to do is removing every space, so use string substitution:

!line: =!

(replace space with nothing)

if there are TABs too, use another !line: =! (that's a TAB, not spaces)

Remove all whitespaces in a file- Linux

Depending on your definition of whitespace, something like:

tr -d ' \t\n\r\f' <inputFile >outputFile

would do the trick.



Related Topics



Leave a reply



Submit