从awk导出变量

时间:2014-03-04 11:51:27

标签: bash variables awk export

我有这个相当简单的脚本

#!/bin/bash

awk -v channels=4096 '{for (i=1;i<=NF;i++) $i=$i-(i-1)*channels} END{printf "There are %d detectors\n ",detectors=NF;}1' $1.dat >$1_Processed.dat
rm -f $1.dat
printf "There are %d detectors\n",$detectors
exit 0

我要做的是打印awk读取的字段数(NF)。因此,对于变量detectors,我总是得到0。

有解决方法吗?

修改

完整的脚本是

#!/bin/bash

if test $1 ; then
   if [ -f $1.evnt ] ; then
      rm -f $1.dat
      sed -n '2p' $1.evnt | (read v1 v2 v3
      for filename in $1*.evnt ; do
         echo -e "Processing file $filename"
         sed '$d' < $filename > $1_tmp
         sed -i '/Kmax/d' $1_tmp
         sed -i '/^'"$v1"' '"$v2"' /d' $1_tmp
         cat $1_tmp >> $1.dat
      done
      v3=`wc -l $1.dat | awk '{print $1}' `
      echo -e "$v1 $v2 $v3" > .$1.dat
      rm -f $1_tmp)
   else
      echo -e "\a!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
      echo -e "  Event file $1.evnt doesn't exist  !!!!!!"
      echo -e "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
   fi   
else
   echo -e "\a!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
   echo -e "!!!!!  Give name for event files  !!!!!"
   echo -e "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
fi
detectors=$(awk -v channels=4096 '{for (i=1;i<=NF;i++) $i=$i-(i-1)*channels} END{print NF;}1' $1.dat >$1_Processed.dat)
#awk -v channels=4096 '{for (i=1;i<=NF;i++) $i=$i-(i-1)*channels} END{printf "There are %d detectors\n ",detectors=NF;}1' $1.dat >$1_Processed.dat
rm -f $1.dat
printf "There are %d detectors\n",$detectors
exit 0

典型的输入文件是

Kmax Event File - Text Format
1 6 1000 
1623 5730 8209 12307 16398 20495 
1505 5611 8208 12306 16395 20497 
934 5036 8208 12308 16399 20498 
1552 5656 8208 12306 16396 20495 
1622 5729 8208 12305 16397 20495 
1526 5631 8207 12305 16397 20496 
1522 5629 8208 12307 16396 20497 
1525 5630 8208 12306 16399 20496 
1625 5730 8208 12305 16396 20496 
1717 5822 8207 12305 16398 20495 
1690 5796 8209 12306 16397 20496 
1525 5630 8209 12305 16399 20495 
1625 5731 8208 12305 16397 20495 
1523 5629 8209 12307 16398 20497 
1719 5825 8208 12307 16398 20495 
1714 5821 8207 12305 16395 20496 
1525 5630 8208 12306 16399 20495 
1528 5634 8209 12306 16396 20496 
1624 5729 8208 12307 16397 20496 
1625 5729 8208 12305 16397 20495 
1524 5630 8209 12305 16397 20495 
1393 5497 8207 12306 16397 20495

1 个答案:

答案 0 :(得分:2)

你可能想要这个:

detectors=$(
    awk -v channels=4096 '
        {for (i=1;i<=NF;i++) $i=$i-(i-1)*channels; print} 
        END {print NF > "/dev/stderr"}
    ' $1.dat 2>&1 >$1_Processed.dat
)

重定向:

  • 首先,fd 2被重定向到当前指向
  • 的fd 1
  • 然后将fd 1重定向到一个文件(影响fd 2现在指向的那个)
  • 测试:

    $ x=$(awk 'BEGIN {print "stdout"; print "stderr" > "/dev/stderr"}' 2>&1 >/tmp/foo)
    $ echo "$x"
    stderr
    $ cat /tmp/foo
    stdout
    

表单print NF > "/dev/stderr" 可能特定于GNU awk。

我注意到第二行的第二个字段也是6.如果这是检测器的数量,则提取它是一种更明显的方法。

detectors=$( awk 'NR==2 {print $2; exit}' $1.dat )
# or
read a detectors b < <(sed -n '2{p;q}' $1.dat)