Awk

如何在awk中動態傳遞值

  • January 27, 2020

我正在嘗試將包含太多行的 csv 文件拆分為使用者定義的塊。行數,使用以下腳本,使用awk但它不生成任何輸出,文件被創建但它是空白的。請任何人都可以指出缺少什麼…

# !/bin/bash
File=filename.csv
count=`awk 'END {print NR}' $File`
i=2
j=5000
k=$j
while [ $j -le $count ]
 do
   awk 'NR==1 {print $0}' $File > output"$i".csv
   awk 'NR==$i, NR==$j {print $0}' $File > output"$i".csv
   i=`expr $j + 1`
   j=`expr $i + $k`
   if [ $j -gt $count ]
     then
       j=$count
       k=`expr 0 - 1`
   elif [ $j -eq $count]
     then
       break
   fi
done

如果你真的想用awk那麼怎麼樣

awk -v c=5000 '
   BEGIN{getline; head=$0; f = -1}
   {if (f != int((NR-2)/c)) {f+=1; fl=sprintf("%03d.csv", f); print head > fl}; print $0 > fl}
   ' filename.csv

至於你的劇本……

#!/bin/bash
File=filename.csv
count=$(awk 'END {print NR}' $File) # syntax
i=2
j=5000
k=$j
while [ $j -le $count ]
 do
   awk 'NR==1 {print $0}' $File > output"$i".csv
   # you cannot pass shell variables directly into awk, use -v
   # and append >> don't overwrite >
   awk -v st=$i -v fi=$j 'NR==st, NR==fi {print $0}' $File >> output"$i".csv 
   i=`expr $j + 1`
   j=`expr $i + $k`
   if [ $j -gt $count ]
     then
       j=$count
       k=-1
   elif [ $j -eq $count ] # needed a space before the ]
     then
       break
   fi
done

引用自:https://unix.stackexchange.com/questions/564404