我有一個包含以下列的檔案(in.txt):
# DM Sigma Time (s) Sample Downfact
78.20 7.36 134.200512 2096883 70
78.20 7.21 144.099904 2251561 70
78.20 9.99 148.872384 2326131 150
78.20 10.77 283.249664 4425776 45
我想撰寫一個 bash 腳本來將“時間”列中的所有值除以 0.5867,獲得高達 2 個小數點的精度并在另一個檔案 out.txt 中列印出結果值
我嘗試使用 bc/awk 但它給出了這個錯誤。
awk: cmd. line:1: fatal: division by zero attempted
awk: fatal: cannot open file `file' for reading (No such file or directory)
有人可以幫我解決這個問題嗎?謝謝。
這是我嘗試的 bash 腳本:
cat in.txt | while read DM Sigma Time Sample Downfact; do
echo "$DM $Sigma $Time $Sample $Downfact"
pperiod = 0.5867
awk -v n=$Time 'BEGIN {printf "%.2f\n", (n/$pperiod)}'
#echo "scale=2 ; $Time / $pperiod" | bc
#echo "$subint" > out.txt
done
我希望腳本將“時間”列與 pperiod 分開,并以 2 位小數的精度獲得結果。此結果應列印到名為 out.txt 的檔案中
uj5u.com熱心網友回復:
awk當前代碼存在很多問題:
- 需要傳入
$pperiod變數的值 - 需要
Time按位置參考列($3在這種情況下) BEGIN{}塊在處理任何輸入行之前應用,與實際輸入行的處理無關- 沒有對實際輸入行執行處理的代碼
- 需要決定在某種
divide by zero情況下要做什么(在這種情況下,我們將默認回答0.00) - 注意:當前代碼會產生
divide by zero錯誤,因為$pperiod它是一個未定義的 (awk) 變數,而該變數又默認為0 - 另外,
pperiod = 0.5867是無效的bash語法
解決當前問題的一個想法:
pperiod=0.5867
awk -v pp="${pperiod}" 'NR>1 {printf "%.2f\n", (pp==0 ? 0 : ($3/pp))}' in.txt > out.txt
在哪里:
-v pp="${pperiod}"- 為變數賦值變數awk的pp值bash"${pperiod}"NR>1- 跳過標題行NR>1{printf "%.2f\n" ...}- for each input line, other than the header line, print the result of dividing the時間column (aka$3) by the value of theawkvariablepp(which holds the value of thebashvariable"${pperiod}"`)(pp==0 ? 0 : ($3/pp))- 如果pp等于 0,我們列印0else 列印結果$3/pp)(這使我們無法生成 adivide by zero error)- 注意:這也消除了
cat|while回圈的需要
這會產生:
$ cat out.txt
228.74
245.61
253.75
482.78
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/520793.html
標籤:重击壳
上一篇:與bashfor回圈并行化
下一篇:bash腳本中的跳線
