Shell 脚本 - 剪切文件中特定关键字的所有字符串

Shell scripting - cut all the strings of a specific keyword in a file

我正在尝试制作一个脚本,该脚本接收一个日志文件,其中每一行都包含一个名称 + >tab< + 运行时间(数字),如下所示:

calloffice      14
name    15
other   16
CallOffice      18

我想做的是找到与给定名称匹配的所有行,然后将运行时编号加在一起。

所以我首先让他们打印出来。但是我的脚本应该能够在 logg 文件中搜索关键字并仅从该关键字获取所有不同的运行时,现在我从所有数字而不是仅关键字运行时获取运行时。

这是我目前所做的:

#!/bin/bash
echo "What is the event?"

FILE=

while read text
do
    if grep "$text" hendelse.txt; then

    $text | cut -f2 -d$'\t' hendelse.txt

else 
    echo "text not found"
fi
done

我知道我还没有接近脚本的终点线,但我的问题是如何从特定关键字获取运行时数字?

您应该使用带有制表符作为分隔符的 awk (awk -F"\t")

假设您将所有运行时和名称放在一个由制表符分隔的文件中。

你应该这样做(在本例中关键字是 calloffice):

~$ cat test.txt 
calloffice 14
name 15
other 16

~$ grep calloffice test.txt 
calloffice 14

~$ grep calloffice test.txt |awk -F"\t" '{print }'
14

您的结果是 14,这是给定关键字的运行时间。注意是调用print的第二个参数($2)的结果。

根据原始问题和从 OP 评论中提取的部分:

  • 文件中可能有多个匹配行
  • 对于所有匹配的行,将运行时间加在一起
  • 需要使用不区分大小写的字符串匹配

示例输入文件:

$ cat test.txt
calloffice      14
name    15
other   16
CallOffice      18

一种可能的awk解决方案:

BEGIN {total=0}
tolower()==str {total+=}
END {printf "total : %s\n",total}
  • BEGIN {total=0} : 初始化我们的总数
  • tolower()==str :小写字段 #1(允许不区分大小写的匹配),如果等于我们的输入字符串 str 那么 ...
  • total+= :将我们的总数增加字段 #2
  • 中的金额

并且 awk 脚本在传递 'calloffice':

的搜索字符串时起作用
$ awk '
BEGIN {total=0}
tolower()==str {total+=}
END {printf "%s total : %s\n",str,total}
' str="calloffice" test.txt

calloffice total : 32