gpt4 book ai didi

java - Java 中的 awk 命令

转载 作者:行者123 更新时间:2023-12-01 06:08:38 24 4
gpt4 key购买 nike

我想在 Java 中使用 awk 命令行。为此,我有这段代码(我在教程中看到了这段代码):

Map map = new HashMap();
map.put("file", new File(fileDirectory));

CommandLine cmdLine = new CommandLine("awk");
cmdLine.addArgument("{print $1}", false);
cmdLine.addArgument("${file}");
cmdLine.setSubstitutionMap(map);
System.out.println(cmdLine.toString());

DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
ExecuteWatchdog watchdog = new ExecuteWatchdog(10000);
DefaultExecutor executor = new DefaultExecutor();
executor.setWatchdog(watchdog);
executor.execute(cmdLine, resultHandler);

resultHandler.waitFor();

在此示例中,我的代码打印文件的第一列。

10
10
10
10
10
10
10
10
10
10
10
10
10
10
10

我想将输出打印到文件中,但我无法弄清楚。

最佳答案

通常,要在 Java 中以编程方式运行 awk 命令,您可以使用 Jawk 。我被要求自己 build 它,但没什么大不了的。我已经使用 1.03 版本进行了测试,以编程方式调用 awk 命令,如下所示,适合我的用例。

            String[] awkArgs= { "-f", awkProgramPath };
// Create a stream to hold the output
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(baos);
// Tell Java to use your byte arrya output stream temporarily
System.setOut(ps);

AwkParameters parameters = new AwkParameters(Main.class, null);
AwkSettings settings = parameters.parseCommandLineArguments(awkArgs);

//Instead of passing file as argument setting the file content as input.
//This is done to adapt the line delimiters in file content to the specific OS. Otherwise Jawk fails in splitting the lines.
//If it is not required, this step cab be skipped and the input file path can be passed as additional argument
String inputFileContent = new String(Files.readAllBytes(inputFile.toPath()));
//Adapting line delimiter.
inputFileContent = inputFileContent.replaceAll("[\r]?\n", System.getProperty("line.separator"));
settings.setInput(new ByteArrayInputStream(inputFileContent.getBytes()));

//Invoking the awk command
Awk awk = new Awk();
awk.invoke(settings);
//Set the old print stream back. May be you can do it in try..finally block to be failsafe.
System.setOut(sysout);
//Get the output from byte array output stream
String output = baos.toString();

您可能需要在类路径中添加 slf4j.jar,这是 jamk.jar 内部所需的。

关于java - Java 中的 awk 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39414814/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com