3
$\begingroup$

In a text file, there are several blank lines and how to remove all of them in a simple way ?

  str="adf{adfadfsa

       dddd sdf sdf,
       dfdsf


       dfsfda


       |df"

After done,

  res="adf{adfadfsa
       dddd sdf sdf,
       dfdsf
       dfsfda
       |df"
$\endgroup$
4
$\begingroup$

The replacement rule "\n" .. -> "\n" will do it, where "\n".. means one or more new lines.

str = "adf{adfadfsa

         dddd sdf sdf,
         dfdsf


         dfsfda


         |df";

StringReplace[str, "\n" .. -> "\n"]

"adf{adfadfsa dddd sdf sdf, dfdsf dfsfda |df"

The same with regular expressions:

StringReplace[str, RegularExpression["\n+"] -> "\n"]

Yet another way:

StringRiffle[StringSplit[str, "\n" ..], "\n"]

And also:

ExportString[DeleteCases[ImportString[str, "Lines"], ""], "Lines"]
$\endgroup$
  • 1
    $\begingroup$ Thanks! I find Tab includes in my text, so StringReplace[str, "\n\t" .. -> "\n"] works. $\endgroup$ – Orders Aug 25 '17 at 4:49

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.