如何防止 awk 中的系统调用返回退出代码,或者如何格式化它?

Flo*_*ain 2 linux awk

使用 awk,该system命令返回命令输出和退出代码。

但是,输出和退出代码之间有一个新行,这是我真的不想要的。

例子:

BEGIN {
    FS = ","
}
{
    print system("echo toto")
}
Run Code Online (Sandbox Code Playgroud)

输出几行文件:

toto
0
toto
0
toto
0
toto
0
toto
0
toto
0
toto
0
toto
0
toto
0
toto
0
toto
0
Run Code Online (Sandbox Code Playgroud)

在另一篇文章中,我尝试了以下方法来删除新行:

printf "%s,", system("echo toto")
Run Code Online (Sandbox Code Playgroud)

但它有以下结果:

toto
0,toto
0,toto
0,toto
0,toto
0,toto
0,toto
0,toto
0,toto
0,toto
0,toto
0,
Run Code Online (Sandbox Code Playgroud)

我怎样才能:

  • 阻止系统调用返回退出代码?
  • 正确格式化输出和退出代码,以便每个退出代码位于命令输出之后(或之前)?

dav*_*085 6

awksystem()永远不会“返回”任何输出。如果它运行的命令写入输出,则输出会直接进入而不对标准输出进行任何修改 - 在您的情况下,因为您没有将其重定向到您的终端。system()返回退出状态,并再次将该状态加上换行符打印到标准输出,因为您没有重定向它。print system()

要捕获命令的输出并在 awk 中对其进行操作,请stringcommand | getline [var]在必要时使用repeated来获取多行,并在必要时使用repeated来close(stringcommand)获取状态。

$ seq 5 | awk '{"echo toto"|getline x; print NR ":x=" x ",status=" close("echo toto") " and Robert is the brother of your parent"}'
1:x=toto,status=0 and Robert is the brother of your parent
2:x=toto,status=0 and Robert is the brother of your parent
3:x=toto,status=0 and Robert is the brother of your parent
4:x=toto,status=0 and Robert is the brother of your parent
5:x=toto,status=0 and Robert is the brother of your parent
Run Code Online (Sandbox Code Playgroud)