2013-01-31 86 views
22

我有一个C程序,我想通过在shell脚本中使用awk来调用。我该如何做这样的事情?使用awk调用可执行程序

+1

编译的C程序仅仅是一个程序...只要运行它,就像你的任何命令行操作... – PearsonArtPhoto

+1

你可以叫'系统()'用awk来执行命令。也许你可以进一步解释你的需求,因为有一个更好的方法去做这个> 90%的时间。 – Grambot

+2

这通常是错误的方法。如果你发布一个小awk脚本,并解释当你想打电话给你的C程序,我们可以告诉要么怎么做,或有什么更好的办法是。 –

回答

29

从AWK手册页:

 
system(cmd) 
       executes cmd and returns its exit status 

的GNU AWK manual也有a section,在部分,介绍了system功能,并提供了一个示例:

system("date | mail -s 'awk run done' root") 
+0

感谢您的帮助!我在busybox中有一个shell命令:logread -f | awk {if .....}和awk内部,当if语句对参数为真时,我想在c中调用我的程序。你能给我一个提示吗? – user2030431

+1

尝试'logread -f | AWK“{如果(condition01){系统(‘yourCprogram参数’)}}”' – nullrevolution

+0

@ user2030431你会是不错的读者,如果你将更新所有/详细信息您的问题。是的,我知道它有点晚了:) – Felix

19

有几种方法。

  1. awk有一个system()功能,将运行shell命令:

    system("cmd")

  2. 您可以打印到管道:

    print "blah" | "cmd"

  3. 你可以有AWK构建命令,并将所有输出传递给shell:

    awk 'some script' | sh

4

东西这么简单将工作

awk 'BEGIN{system("echo hello")}' 

awk 'BEGIN { system("date"); close("date")}'

1

这真的取决于:)在方便的Linux核心utils软件包(info coreutils )是xargs。如果您使用的是awk,那么您可能需要考虑更多的用例 - 您的问题没有详细说明。

printf "1 2\n3 4" | awk '{ print $2 }' | xargs touch 

将执行touch 2 4。这里touch可以被你的程序替换。更多信息在info xargsman xargs(真的,阅读这些)。 我相信你想用你的程序替换touch

击穿beforementioned脚本

printf "1 2\n3 4" 
# Output: 
1 2 
3 4 

# The pipe (|) makes the output of the left command the input of 
# the right command (simplified) 
printf "1 2\n3 4" | awk '{ print $2 }' 
# Output (of the awk command): 
2 
4 

# xargs will execute a command with arguments. The arguments 
# are made up taking the input to xargs (in this case the output 
# of the awk command, which is "2 4". 
printf "1 2\n3 4" | awk '{ print $2 }' | xargs touch 
# No output, but executes: `touch 2 4` which will create (or update 
# timestamp if the files already exist) files with the name "2" and "4" 

更新在原来的答案,我用echo代替printf。然而,printf是一个更好,更便携的选择,正如评论指出的那样(可以找到与讨论有很大联系的地方)。

+0

这不适合我正常工作... – MountainX

+0

@MountainX在哪种方式它的工作原理(错误地)?你使用哪种操作系统和外壳? – Felix

+0

在Arch Linux的和bash,这里是我的结果:[用户@ COMP1〜] $回声 “1点2 \ N3 4” | awk'{print $ 2}'| xargs的触摸 [用户@ COMP1〜] $ LS -LA -rw-RW ---- 1个用户的用户0 03月07日13时34分2N3 – MountainX

2
#!/usr/bin/awk -f 

BEGIN { 
    command = "ls -lh" 

    command |getline 
} 

流程“LS -lh”在awk脚本

+1

你确定这可以吗?这不起作用。 –

0

我用awk的力量来删除一些我停泊坞窗容器。仔细观察我如何构造cmd字符串,然后将其传递给system

docker ps -a | awk '$3 ~ "/bin/clish" { cmd="docker rm "$1;system(cmd)}'

在这里,我使用具有图案“/斌/ clish”第3列,然后我提取容器ID在第一列中,构建我cmd串和通过了给system

0

我能有通过以下方法完成这件事

cat ../logs/em2.log.1 |grep -i 192.168.21.15 |awk '{system(`date`); print $1}' 

awk有一个调用的系统功能它使您能够AWK的输出中执行任何Linux bash命令。