Remove blank lines

I really hope someone can help me with this. I have several php files from a forum that I run, that now for some reason have blank lines after every line. Is there an easy way to make a script that does the following:

  • If there are consecutive blank lines, delete all of them except one.
  • If there is a blank line between lines with text, delete it.

Example - I want this:

<?php

/*

 * @text

 * @text

 * @text



 * @text

 * @text

 * @text


 */

?>

to result in this:

<?php
/*
 * @text
 * @text
 * @text

 * @text
 * @text
 * @text

 */
?>

Anyone?

First sed cleans ends of lines of spaces and tabs (I show \t but I mean a real tab).
Second and third sed's are loopers with N, and so cannot share buffer with others.
Second sed removes the lonesome blank lines by examining three lines in the buffer.
Third sed removes adjacent blank lines by examining two lines in the buffer.

sed '
  s/[ \t][ \t]*$//
 ' | sed '
  :two
  $b
  N
  :one
  $b
  N
  s/\(.)\n\n\(.)/\1\
\2/
  t twox
  P
  s/.*\n//
  t one
  :twox
  P
  s/.*\n//
  t two
 ' | sed '
  :loop
  $b
  N
  /^\n$//!P
  s/.*\n//
  t loop
 '

---------- Post updated at 04:15 PM ---------- Previous update was at 04:14 PM ----------

[/COLOR]The smiley is colon and lower case o.

Thanks for the reply, but I can't get that to work at all. :frowning:

Is there an easier way to do it like this:

  1. Delete all consecutive blank lines except the first, and replace that blank line with a chosen word, with something like this (which just removes consecutive blank lines except the first):
sed '/./,/^$/!d'

If so, I can then just easily remove the rest of the blank lines, and the replace the word I chose with a blank line.

awk 'NF{if(n>1)print x;n=0;print;next}{n++}' infile
1 Like

Awesome, thank you! That works like a charm, exactly how I want it. :slight_smile: :b:

---------- Post updated at 10:31 PM ---------- Previous update was at 10:16 PM ----------

If I would want to do this on a number of .php files in a folder and get the output from each file as filename_2.php, how can I script that too?

 
for file_name in *.php
do
---your awk statement $file_name > ${file_name}"_2".php
done
1 Like

Small correction to panyam's suggestion:

awk-statement "$file_name" > "${file_name%.*}_2.php"
1 Like

Thank you both. :slight_smile:

$ ruby -00 -ne 'print $_.squeeze("\n")' file
<?php
/*
 * @text
 * @text
 * @text

 * @text
 * @text
 * @text

 */
?>

Sorry, I should have tested the final version!

$ echo '<?php

/*

 * @text

 * @text

 * @text



 * @text

 * @text

 * @text


 */

?>'|sed '
  s/[   ][      ]*$//
 ' | sed '
  :two
  $b
  N
  :one
  $b
  N
  s/\(.\)\n\n\(.\)/\1\
\2/
  t twox
  P
  s/.*\n\(.*\n\)/\1/
  t one
  :twox
  P
  s/.*\n//
  t two
 ' | sed '
  :loop
  $b
  N
  /^\n$/!P
  s/.*\n//
  t loop
 '
<?php
/*
 * @text
 * @text
 * @text

 * @text
 * @text
 * @text

 */
?>

$