Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have a 210-line block of HTML that I have stored in a HTML for debugging purposes.

The HTML, as you would expect, is formatted accordingly so is stored in the file with spaces and tabs. Is it possible to convert this file to having all the HTML on one line? I am on CentOS 5.6.

For example, is there an easy way to change this:

<div id="crmpicco">
     <div class="ayrshireminis">
... content in here ...

to this:

<div id="crmpicco"><div class="ayrshireminis"></div></div>
share|improve this question
Do you actually want to minify the file? See this discussion at SO. – Michael Hampton Aug 17 '12 at 20:19

You might find the tr utility helpful. cat INPUT_FILE | tr -d '\n\r' > OUTPUT_FILE seems to do the job.

  • -d Delete characters, instead of translating

See man tr for more details on what more tr can do. Hope this helps.

share|improve this answer

There are many tools you could use to do this. Here's a solution in perl.

On the command line:

perl -p -e 's/^ *//; s/ *$//; chomp' < FILE > OUTFILE

where you replace FILE with the name of the file and OUTFILE with the new file you want the output written to. Do not use the same filename for both.

What it does: perl -p runs a perl script on each line of the input it gets and writes the result to the output. You're setting the input and output with the < and > operators to the files you want. The script itself follows the -e option and does three substitutions.

s/^ *//: substitute any number of spaces (space, star) at the beginning of the line (^) with nothing (the command s/this/that/ changes this to that). If you expect to have TAB characters instead of spaces, do s/^[ \t]*// which substitutes away any number of spaces or tabs (\t).

s/ *$//: same but at the end of the line ($).

chomp: perl-speak for removing the line break at the end of a line.

share|improve this answer
awk '{ORS=""; print $0}' textfile
<div id="crmpicco">     <div class="ayrshireminis">... content in here ...     </div></div>

Additionally, as was already pointed out, the tr utility is awesome for this. To remove newlines and tabs/spaces all at once using the tr utility, do:

# cat textfile |tr -d '\n\r" "'

NOTE: if you have tabs instead of spaces, do

cat textfile |tr -d '\n\r\t'
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.