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

时间:2017-09-06 17:29:15

标签: bash shell delimiter cut

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

calloffice      14
name    15
other   16
CallOffice      18

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

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

这是我到目前为止所做的:

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

FILE=$1

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

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

else 
    echo "text not found"
fi
done

我知道我甚至不在剧本的终点线附近,但我的问题是如何从特定关键字中获取运行时编号?

2 个答案:

答案 0 :(得分:2)

你应该使用awk with tab作为分隔符(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 $2}'
14

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

答案 1 :(得分:1)

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

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

示例输入文件:

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

一种可能的awk解决方案:

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

传递' calloffice'的搜索字符串中的awk脚本:

$ awk '
BEGIN {total=0}
tolower($1)==str {total+=$2}
END {printf "%s total : %s\n",str,total}
' str="calloffice" test.txt

calloffice total : 32