[Bro] Split path into directory and filename

Peter Erickson redlamb19 at gmail.com
Sat Aug 13 18:45:38 PDT 2011

Is there a way use regex to extract portions of a string? I'm trying to
write a function that accepts a path and breaks it into a directory and
filename (/tmp/file.txt => [ /tmp, file.txt ]). I would like to do
something as easy as /(\/.+)/([^\/]+)$/, but am not sure it's possible
with bro (I wrote the expr quick so there are probably typos).

Right now I have the following, but wondering if there is a better way:

function path_split(path: string): string_array {
        local cpath = split(path, /\//);
        local ret_val: string_array;

        ret_val[2] = cpath[length(cpath)];
        delete cpath[length(cpath)];
        ret_val[1] = join_string_array("/", cpath);

        return ret_val;

The reason I ask is I'm looking to modify the http/file-extract.bro
script so that the http responses are saved into a directory structure
based on the src and dst ip addresses (e.g. http-items/src_ip/dst_ip).
I plan to modify the generate_extraction_filename to create this path
and then send the filename to a function to create the directory
structure. (I know that modifying generate_extraction_filename will have
adverse affects on other scripts, but I plan to update those as well.)

If anyone cares, here is the function I wrote to recursively create the
directory structure.

function mkdirs(dir: string): bool {
        local path_split = split1(dir, /\/[^\/]*$/);
        local parent = path_split[1];

        if ( parent == "" || length(path_split) == 1 )
                return mkdir(dir);
        else {
                if ( ! mkdirs(parent) )
                        return F;
                return mkdir(dir);

        return T;

Thanks in advance.

Peter Erickson
redlamb19 _at_ gmail _dot_ com

More information about the Bro mailing list