Odi*_*dil 2 linux bash shell awk
我正在尝试仅使用 awk 命令打印 .csv 文件中某个字段的出现次数。例如在像这样的文件 test.csv 中:
layla;rebel;TAT
han_solo;rebel;TAT
darth_vader;empire;DKS
yoda;rebel;TAT
Run Code Online (Sandbox Code Playgroud)
使用命令:
cat test.csv | ./how_many_are_we.sh dks
Run Code Online (Sandbox Code Playgroud)
我希望有以下输出:
1
Run Code Online (Sandbox Code Playgroud)
这是我在 how_many_are_we.sh 中的代码(工作正常但区分大小写):
#! /bin/bash
awk -F ";" -v location=$1 'BEGIN {count=0;} { if ($3 == location) count+=1} END {print count}'
Run Code Online (Sandbox Code Playgroud)
我尝试IGNORECASE=1在不同的地方添加,但我似乎无法找到正确的方法来使它工作。
请原谅我的措辞不好,并感谢您的帮助。
您可以将输入值的大小写和第三个字段更改为小写,然后比较它们的值以确保它们输入的比较不应该受到影响。
#!/bin/bash
awk -F ";" -v location="$1" 'BEGIN {location=tolower(location);count=0;} { if (tolower($3) == location) count+=1} END {print count+0}' Input_file
Run Code Online (Sandbox Code Playgroud)
或根据格伦先生的评论,使用 shell 技巧将变量本身变为小写。
#!/bin/bash
awk -v location="${1,,}" 'BEGIN{FS=";"} (tolower($3) == location){count+=1} END{print count+0}' Input_file
Run Code Online (Sandbox Code Playgroud)
或更多awksh 方式将awk命令更改为以下(上面是 OP 的命令修复这是使其成为awksh 样式)
awk -v location="$1" 'BEGIN{location=tolower(location);FS=";"} (tolower($3) == location){count+=1} END{print count+0}'
注意:对于 usingIGNORECASE=1,您应该在BEGIN像BEGIN{IGNORECASE=1}OR 像awk变量这样的部分中提及它-v IGNORECASE="1"。
另外附带说明一下,OP 的 shebang 之间有空格#!,/bin/bash这不应该是这种情况,所以我也在这里修复了它。