Deleting new lines with regular expression from Ant task

17,218

Solution 1

This works:

<replaceregexp file="..."
               match="(\r?\n)\s*\r?\n" 
               flags="g"
               replace="\1" />

The point is to match line ends manually and globally (flags="g").

Solution 2

You may use a FilterChain (specifically an IgnoreBlank TokenFilter) to do precisely what you need:

<copy file="${input.file}" toFile="${output.file}">
  <filterchain>
    <ignoreblank/>
  </filterchain>
</copy>

ignoreblank will also remove lines consisting entirely of white space, but looking at your regular expression it seems that is what you want.

Solution 3

I think your issue is with using the start-of-line/end-of-line characters. What you are looking for is blank lines, but what your regular expression appears to search for is a start-of-line followed by 1 or more new lines and/or tabs followed by end-of-line. Shouldn't it be start-of-line followed by end-of-line with nothing in between? So match="^$".

^ The above assumes the regex engine you're using is treating ^$ as start/end of line instead of start/end of the entire input string. If it's the entire input string, your regex would only match empty files, not files that contain some content but also some blank lines.

Solution 4

You can use <filterchain>, reading only the first line and stripping out all the line feeds. Example:

<loadfile property="new.property" srcfile="${input.file}">
    <filterchain>
        <headfilter lines="1" />
        <striplinebreaks />
    </filterchain>
</loadfile>
Share:
17,218
Christopher Dancy
Author by

Christopher Dancy

Software Engineer at Pegasystems.

Updated on June 18, 2022

Comments

  • Christopher Dancy
    Christopher Dancy almost 2 years

    I've posted to 2 forums already (CodeRanch and nabble) and no one has responded with an answer .... so stack overflow ... you are my last hope. All I'm trying to do is delete the "\n" from a file using an Ant task. There simply is a bunch of empty lines in a file and I don't want them there anymore ... here is the code I used ..

        <replaceregexp file="${outputFile}"
         match="^[ \t\n]+$"
         replace=""
         byline="true"/>
    

    It's not picking up the regular expression and I've tried a hundred different ways and I can't figure it out. Any ideas?