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

标签 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"

我现在不添加任何内容,因为首先我需要解决我在 cut 中遇到的这个问题。我遇到的问题是,它不会剪切第一行,但会按照我想要的方式剪切所有其他行。这弄乱了我的 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 只是为了看看是什么导致了错误。

最佳答案

您可以使用 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"

关于linux - Bash:从文件中读取时,剪切不会剪切第一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25765013/

相关文章:

linux - 如何grep值小于或等于值的行

c - 如何在 posix 线程之间发出缓冲区已满状态的信号

java - 即使设置 JAVA_HOME 属性后也会出现错误

linux - unix中同一目录中的多个文件比较

linux - 值的shell脚本比较

linux - 为什么在我的 .bashrc 中使用 `uname` 时出现错误?

linux - 逐行比较两个文件并将匹配项移至第三个文件

linux - 哪些 ncurses 框架可用于 BASH?

linux - 如何在 Linux shell 中复制带空格的多个目录

shell - emacs中的shell和eshell有什么区别?