简体   繁体   English

将AWK中的多个结果保存到Shell变量

[英]Save multiple results from AWK to shell variables

Save multiple results from an AWK script to c shell variables. 将AWK脚本中的多个结果保存到c shell变量中。

I have a simple AWK script running in the terminal to find max and min from an input text file. 我在终端中运行了一个简单的AWK脚本,以从输入文本文件中查找最大值和最小值。

How do we save this max and min values to c shell variable in order to use it later. 我们如何将这个最大值和最小值保存到c shell变量中以便以后使用。

Here is the AWK 这是AWK

awk 'NR == 1 { xmax=$1; xmin=$1 } \
    { if ($1>xmax) xmax=$1; if ($1<xmin) xmin=$1;} \
    END {printf "X-Min: %d\tX-Max: %d\n", xmin, xmax}' $inpfile

I want to save this in already defined variables lets say $xmin and $xmax 我想将其保存在已定义的变量中,比如说$ xmin和$ xmax

Any suggestion would be a great help, I have no prior experience with SHELL and AWK. 任何建议都会有很大帮助,我以前没有使用SHELL和AWK的经验。

As others have said, you can't pass values from awk to the shell. 正如其他人所说,您不能将值从awk传递到外壳。

You'll need to rely on the shells ability to perform cmd-substitution. 您需要依靠shell的功能来执行cmd替换。

Back when all I had was csh, I would have done 当我只有csh时,我会做的

setenv xmin_xmax = `awk 'NR == 1 { xmax=$1; xmin=$1 } \
{ if ($1>xmax) xmax=$1; if ($1<xmin) xmin=$1; printf("%d|%d\n", xmin, xmax}' $inpfile`

setenv xmin = `echo "$xmin_xmax" | sed 's/|.*$//'`
setenv xmax = `echo "$xmin_xmax" | sed 's/*.|//'`

Sorry but I don't have access to a csh to test this with now. 抱歉,但是我现在无法访问csh进行测试。 As you're inside a cmd-substitution with your awk, you'll probably need more continuation chars \\ to connect those lines. 由于您使用awk替换为cmd,因此可能需要更多的继续字符\\来连接这些行。

If you have trouble with this, post the error messages as comments, and I'll see if I can remember the special csh incantations. 如果您对此有疑问,请将错误消息作为注释发布,我将看看我是否还记得特殊的csh咒语。

EDIT Or see Grymoire CSH tips for how to use array variables in csh. 编辑或查看有关如何在csh中使用数组变量的Grymoire CSH技巧 (I don't recall this!) (我不记得了!)

IHTH IHTH

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM