2016-07-25 93 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"