Bash:从文件中读取时,剪切不会剪切第一行

时间:2014-09-10 12:05:54

标签: linux bash shell cut

我正在尝试在bash中创建一个shell脚本,它将日志文件作为参数,然后要求在文件中搜索事件。日志文件如下所示:

CallTilEdb  8
CallCustomer    9
CallTilEdb  4
CustomerChk 10
CustomerChk 15
CallTilEdb  16

首先是事件的名称,然后是时间,由选项卡分隔。 bash脚本的要点是搜索指定的事件并添加在该事件上花费的总时间。到目前为止我的脚本看起来像这样:

#!/bin/bash

declare -i sumTime=0

echo "Which event do you want to search for?"
read event

while read -r line
do
    echo $line; cut -f1
    if [ $(echo $line; cut -f1) == $event ];then
        echo $line; cut -f2
    fi
done < $1


echo "The sum is $sumTime"

我现在没有添加任何东西,因为首先我需要解决这个问题。我遇到的问题是,它不会削减第一行,但它会以我想要的方式切割所有其他行。这弄乱了我的if语句,给出了太多的论据。这是我现在运行脚本的结果:

Which event do you want to search for?
CallTilEdb
CallTilEdb 8 #first line of the file
CallCustomer
CallTilEdb
CustomerChk
CustomerChk
CallTilEdb
bin/vistid.sh: line 11: [: too many arguments
The sum is 0

我对bash很新,所以这可能是一个愚蠢的问题,但我无法理解它。任何有关我如何解决这个问题的指南都非常感谢。

PS:现在回显f1只是为了看看导致错误的原因。

2 个答案:

答案 0 :(得分:2)

您可以使用read本身将该行拆分为两个字段。

#!/bin/bash

declare -i sumTime=0

echo "Which event do you want to search for?"
read event

while read -r column1 column2
do
    if [ "$column1" = "$event" ];then
        sumTime+=$column2
    fi
done < "$1"


echo "The sum is $sumTime"

答案 1 :(得分:0)

或者,您基本上可以使用一行来实现计数循环,例如

$ grep CallTilEdb data | tr -s ' ' |  cut -f 2 -d ' ' | awk '{total = total + $1}END{print "The sum is " total}'
The sum is 28
相关问题