32

How would I remove ALL whitespaces in a given file in Linux?

1
  • Within the file itself or in the file name? Commented Nov 5, 2010 at 20:07

4 Answers 4

67

Depending on your definition of whitespace, something like:

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

would do the trick.

Sign up to request clarification or add additional context in comments.

7 Comments

+1 tr is "cheaper" than sed and you avoid invoking two programs
GNU tr has the class [:space:] for "all horizontal or vertical whitespace" (I assume "or" should be "and"). So tr -d '[:space:]' should do the trick too.
I don't thing that tr works correctly on UTF-8 data, nor even ISO-8859-1, but only on mere ASCII.
@tchrist: Some versions of tr will handle other character sets. In non-ASCII cases the use of [:space:] is probably advised.
this answer if am not mistaken would also delete new line character which is not the objective here. tr -d ' \t\r\f' should instead be used which does not remove the new line character
|
16
sed 's/\s//g' input.txt | tr -d '\n'

1 Comment

Can you please explain why \s in 's/\s//g' means whitespace? Thanks.
11
sed 's/\s//g'|tr -d '\n'

Comments

3

If you have UTF-8 data, best do this:

perl -CS -pe 's/\p{Space}//g' < input > output

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.