2

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 ...
     </div>
</div> 

to this:

<div id="crmpicco"><div class="ayrshireminis"></div></div>
5

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.

2

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.

0
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" "'
<divid=crmpicco><divclass=ayrshireminis>...contentinhere...</div></div>

NOTE: if you have tabs instead of spaces, do

cat textfile |tr -d '\n\r\t'

Your Answer

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

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