Search code examples
javacommand-line-argumentsapache-commons-cli

parsing command line arguments based on '='


I am using apache commons.cli library to parse the command line arguments. The default parsing behavior is that it parses the arguments based on space. I am using ant to pass arguments to my Java program and the ant is using a slightly different syntax and is using = instead of space. How can I change the behavior of my parsing that it parses based on = and not space ? My parsing currently looks like this :

    Options options = new Options();
    options.addOption("Dkey", true, "some parameter");
    CommandLineParser parser = new PosixParser();
    CommandLine cmd = parser.parse(options, args);

Solution

  • Have a look at the usage examples page, especially the Ant example.

    You could use the OptionBuilder and create an option for D which has 2 arguments.

    For your case the adapted example from that page could look like this:

    Option property  = OptionBuilder.withArgName( "key=value" )
                                .hasArgs(2)
                                .withValueSeparator()
                                .withDescription( "use value for given property" )
                                .create( "D" );
    

    Here's the relevant JavaDoc with another example: http://commons.apache.org/cli/api-1.2/org/apache/commons/cli/OptionBuilder.html#withValueSeparator%28%29

    Option opt = OptionBuilder.withValueSeparator().create('D');
    
    CommandLine line = parser.parse(args);
    String propertyName = opt.getValue(0);
    String propertyValue = opt.getValue(1);