用awk将行号和第一个单词传递给变量

时间:2017-08-13 12:44:06

标签: bash shell awk

我想将下面脚本的“$ 1”和“NR”值分别传递给变量“word”和“line”,而不是打印它们。


    awk '\
    BEGIN { \
    s = 0; \
    } \
    { \
    s += $2; \
    if (s >= 87) { \
    print $1; \
    print NR; \
    exit; \
    } \
    }' file

1 个答案:

答案 0 :(得分:3)

You can let awk dislay the settings that you want (you do not need backslashes between the awk quotes).

awk '
BEGIN { s = 0; }
{
   s += $2;
   if (s >= 87) {
      print "word=\"" $1 "\"";
      print "line=" NR;
      exit;
   }
}' file

You want the output processed. You can do this with

source <(awk '
BEGIN { s = 0; }
{
   s += $2;
   if (s >= 87) {
      print "word=\"" $1 "\"";
      print "line=" NR;
      exit;
   }
}' file)

EDIT: See comments: the awk command can be shorter. I also replaced the source with a read:

read -r word line < <(awk ' {s += $2} s >= 87 { print $1 " " NR; exit; }' file )