2016-07-25 58 views
1

我有一個文件(下面提取)讀文件時,如果變量是零不輸出線

1468929555,4,  0.0000, 999999.0000,  0.0000,0,0,0,0,0 
1468929555,5,  0.4810,  0.0080,  67.0200,0,4204,0,0,0 
1468929555,6,  0.1290,  0.0120,  0.4100,0,16,0,0,0 
1468929555,7,  0.0000, 999999.0000,  0.0000,0,0,0,0,0 

我想在此文件中,並輸出結果到另一文件中讀取,改變Unix時間到人類可讀 - 但我只想在字段7填充時執行此操作。

#!/bin/bash 
file="monitor_a.log" 
host=`hostname` 
while IFS=, read -r f1 f2 f3 f4 f5 f6 f7 f8 f9 f10 
do 
mod_time=`date -d @$f1 +"%d/%m/%y %H:%M:%S"` 

if [[$f7=="0"]]; 
then 
done <"$file" 
fi 

echo "$mod_time,300 ,$host, Apache-a, $f2 , $f5 , $f4 , $f3 , $f7 , $f8 ,   $f9 ,$f6, $f10" >> mod_monitor_a.log 

done <"$file" 

問題就出在我的if語句,我得到的錯誤

./monitor_convert.sh: line 12: syntax error near unexpected token `done' 
./monitor_convert.sh: line 12: ` done <"$file"' 

我的想法在if語句,如果字段7 = 0時,回到文件讀入陣,完成<「$ file」位。 這顯然是不正確的,但我不能工作如何錯過這一行。

謝謝。

+2

在http://www.shellcheck.net/中粘貼腳本顯示問題:'if [[$ f7 ==「0」]]'是錯誤的,您需要括號內的空格。 – fedorqui

回答

1

有兩個問題:

if [[$f7=="0"]]需求空間,而 「完成」 這裏面如果應該是一個繼續:

#!/bin/bash 
file="monitor_a.log" 
host=`hostname` 
while IFS=, read -r f1 f2 f3 f4 f5 f6 f7 f8 f9 f10 
do 
    mod_time=`date -d @$f1 +"%d/%m/%y %H:%M:%S"` 

    if [[ $f7 == "0.0000" ]] 
    then 
    continue 
    fi 

    echo "$mod_time,300 ,$host, Apache-a, $f2 , $f5 , $f4 , $f3 , $f7 , $f8 ,   $f9 ,$f6, $f10" >> mod_monitor_a.log 

done <"$file" 
+0

謝謝大家。我最終將if語句設置爲不等於,並在if語句內寫入文件。 #######將文件讀入以逗號分隔的數組 ,同時IFS =,讀取-r f1 f2 f3 f4 f5 f6 f7 f8 f9 f10 do #######修改Unix時間到人類可讀 mod_time ='date -d @ $ f1 +「%d /%m /%y%H:%M:%S」' #######刪除所有域沒有擊中 if [[$ f7 =「0」]] then printf'%s \ n'「$ f7」 echo「$ mod_time,300,$ host,Apache-a,$ f2,$ f5,$ f4,$ f3,$ f7 ,$ f8,$ f9,$ f6,$ f10「>> mod_monitor_a.log fi done <」$ file「 – user3615267

2

的語法問題一串: -

  1. bash if-construct,它應該是if [[ $f7 == "0" ]];而不是if [[$f7=="0"]];
  2. 行號10,done <"$file",語法不允許。如果您打算打破/繼續循環,只需使用break/continue構造。
  3. 不要使用傳統的命令替換使用``,而採用$(..),請參考page的原因。

重新格式化zero問題/警告腳本http://www.shellcheck.net/

#!/bin/bash 
file="monitor_a.log" 
host=$(hostname) 
while IFS=, read -r f1 f2 f3 f4 f5 f6 f7 f8 f9 f10 
do 
    mod_time=$(date -d @"$f1" +"%d/%m/%y %H:%M:%S") 

    if [[ $f7 == "0" ]]; 
    then 
    continue # Process the remaining lines 
    fi 

    echo "$mod_time,300 ,$host, Apache-a, $f2 , $f5 , $f4 , $f3 , $f7 , $f8 ,   $f9 ,$f6, $f10" >> mod_monitor_a.log 

done <"$file" 
0

這是最終爲我工作,帶來了寫入新文件中的if語句中的代碼。

#!/bin/bash 
file="monitor_a.log" 
host=`hostname` 
#######Read in file to array separated by comma 
while IFS=, read -r f1 f2 f3 f4 f5 f6 f7 f8 f9 f10 
do 
#######Modify Unix time to human readable 
mod_time=`date -d @$f1 +"%d/%m/%y %H:%M:%S"` 

#######Remove all Domains without a hit 
if [[ $f7 != "0" ]] 
then 
    printf '%s\n' "$f7" 
    echo "$mod_time,300 ,$host, Apache-a, $f2 , $f5 , $f4 , $f3 , $f7 , $f8 , $f9 ,$f6, $f10" >> /home/saengers/mod_monitor_a.log 
fi 

done <"$file"