clamp
clamp

Reputation: 34036

Remove lines containing keyword from a file

I would like to remove all lines from a textfile which contain a certain keyword.

So far I only found:

<linecontains>
    <contains value="assert"/>
</linecontains>

but I don't know how to remove those lines.

Upvotes: 15

Views: 11212

Answers (2)

ewan.chalmers
ewan.chalmers

Reputation: 16245

You would use that filter in a filterchain, in a task which supports the filterchain element, i.e. the built-in Concat, Copy, LoadFile, LoadProperties, Move tasks.

So, for example, copy or move the file using a filterchain containing your linecontains filter.

Use the negate parameter on your linecontains filter to exclude lines containing that string.

Example:

<project default="test">
    <target name="test">
        <copy tofile="file.txt.edit" file="file.txt">
            <filterchain>
                <linecontains negate="true">
                    <contains value="assert"/>
                </linecontains>
            </filterchain>
        </copy>
    </target>
</project>

Before:

$ cat file.txt
abc
assert
def
assert
ghi assert
jkl

After:

$ cat file.txt.edit
abc
def
jkl

To answer your followup question on applying to selected files in a directory:

<copy todir="dest">
    <fileset dir="src">
        <include name="**/*.txt"/>
    </fileset>
    <filterchain>
        <linecontains negate="true">
            <contains value="assert"/>
        </linecontains>
    </filterchain>
</copy>

Upvotes: 30

mihaisimi
mihaisimi

Reputation: 1999

You could execute an external command.

I haven't tested but on UNIX you might run something like this:

<exec executable="sed">
    <arg value="s/assert//" />
   <arg value="YOUR_FILE" />
</exec>

Upvotes: 0

Related Questions