Question

I want to copy lines from a log file to separate files. It should copy only those lines which contains the ip from given list.

//EDIT - more verbose code for tests Here's my code:

static String[] ips = [
"192.168.1.2",
"192.168.1.1"
];

public static void main(String[] args) {

    AntBuilder ant = new AntBuilder();

    String folder = 'C:/logs';

    ips.each {
        String ip = it;
        File file = new File("${folder}/singular_incidents/${ip}.txt")
        ant.copy(tofile:"${folder}/singular_incidents/${ip}.txt"){
            fileset(dir: folder){
                include(name:"*access*.log")
            }
            filterchain(){
                linecontains(){
                    contains(ip)
                }
            }
        }
    }
}

AND log file (accesslog-2014-05-05.log) contents could look like this

192.168.1.1 - user1 [24/Apr/2014:15:51:06 +0200] 'GET HTTP/1.1' 192.168.1.1 - user1 [24/Apr/2014:15:51:38 +0200] 'POST ' 192.168.1.2 - user2 [24/Apr/2014:15:51:40 +0200] 'POST ' 192.168.1.3 - user3 [24/Apr/2014:16:60:40 +0200] 'POST '

The goal is that I should get two separate files with names - 192.168.1.1.txt - containing two first lines - 192.168.1.2.txt - containing third line

Unfortunately when using linecontains I get this error (I've obfuscated actual ip string):

Caught: class org.apache.tools.ant.filters.LineContains$Contains doesn't support nested text data ("555.555.555.555")

Was it helpful?

Solution

Hope this helps You:

String[] ips = [
    "192.168.1.2",
    "192.168.1.1"
]

def ant = new AntBuilder()
def dest = new File('/tmp')
new File('.').eachFileMatch(~/access.*.log/) { log ->
   ips.each { ip ->
        File file = new File(dest, "${ip}.txt")
        ant.copy(file: log.name, tofile: "$dest.absolutePath/${ip}.txt") {
            filterchain() {
                linecontains() {
                    contains(value: "$ip")
                }
            }
        }
    } 
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top