【问题标题】:using awk or other shell command inside gnuplot function在 gnuplot 函数中使用 awk 或其他 shell 命令
【发布时间】:2012-10-11 19:03:03
【问题描述】:

我想要这样的东西:

file1='logs/last/mydata1.log'
file2='logs/last/mydata2.log'

# declare function that uses awk to reshape the data - does not work :(
sum1(fname)=("<awk '{sum=0; for(i=8;i<=NF;i+=2) sum+=$i; print $1,sum/2}' $fname")
sum2(fname)=("<awk '{sum=0; for(i=9;i<=NF;i+=2) sum+=$i; print $1,sum/2}' $fname")

# plot different columns of my file and awk processed file
plot file1 u 1:2 title "thing A measure 1" w l, \
     file1 u 3:4 title "thing A measure 2" w l, \
     file2 u 1:2 title "thing B measure 1" w l, \
     file2 u 3:4 title "thing B measure 2" w l, \
     sum1(file1) u 1:2 title "group A measure 1" w l, \
     sum2(file1) u 1:2 title "group A measure 2" w l, \
     sum1(file2) u 1:2 title "group B measure 1" w l, \
     sum2(file2) u 1:2 title "group B measure 2" w l

不工作的是在 gnuplot 函数中带有 awk 的部分。 在plot 之后直接使用我的awk 脚本可以正常工作:

plot "<awk '{sum=0; for(i=9;i<=NF;i+=2) sum+=$i; print $1,sum}' ./logs/last/mydata1.log" u 1:2 w l

有没有办法将awk 或其他shell 命令放入gnuplot 函数中? 我知道我可以将 awk 脚本外包给另一个文件,然后在 plot 之后直接 awk 这个文件,但我不想要单独的文件。

【问题讨论】:

    标签: awk gnuplot


    【解决方案1】:

    $var 不会像在 shell 中那样在 gnuplot 中的字符串中扩展 var。您想使用 gnuplot 的字符串连接(使用 . 运算符):

    sum1(fname)="<awk '{sum=0; for(i=8;i<=NF;i+=2) sum+=$i; print $1,sum/2}' ".fname
    

    或者,如果您觉得更舒服,我想您可以使用sprintf

    sum1(fname)=sprintf("<awk '{sum=0; for(i=8;i<=NF;i+=2) sum+=$i; print $1,sum/2}' %s",fname)
    

    *请注意,这实际上并不执行命令。它只是构建将传递给plot 的字符串,然后plot 将执行命令。如果你真的想在一个函数中执行一个命令,你可以调用system作为一个函数。来自文档:

    `system "command"` executes "command" using the standard shell. See `shell`.
     If called as a function, `system("command")` returns the resulting character
     stream from stdout as a string.  One optional trailing newline is ignored.
    
     This can be used to import external functions into gnuplot scripts:
    
           f(x) = real(system(sprintf("somecommand %f", x)))
    

    【讨论】:

    • 完美!我现在还添加了另一个帮助函数exec(cmd,arg1)=(system(sprintf(cmd, arg1))),这让我不必多次重新输入system(sprintf())
    • 我刚刚看到我的exec 不适用于plot。正如您所说,plot 需要一个字符串,由您的第二个 sn-p 生成。感谢您指出这一点。
    猜你喜欢
    • 1970-01-01
    • 2019-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多