您正在從混合構建Awk
和bash
在一起。假設你想在Awk
你需要做的if-else
條款,
awk -F'#' '$3 == "A" && $4 == "B"{c+=$2;} END{printf "count=%d\n",c}' file.csv
count=41
爲我公司生產的
$ cat file.csv
junk#21#A#B
junk#22#C#D
junk#20#A#B
junk#19#D#E
即statment '$3 == "A" && $4 == "B"
樣本輸入隱含意味着做和運算只有$3
平等的行動A
和$4
等於B
if
的明確用法可以做成某事下面,
awk -F'#' '{if ($3 == "A" && $4 == "B") {c+=$2;}} END{printf "count=%d\n",c}' file
count=41
這是不建議使用純bash
腳本解析/遍歷文件,但對於純粹的做法,如果你想辦法,你可以這樣做
#!/bin/bash
unset count
# The '_' in read implies ignore rest of the line
while IFS='#' read -r col1 col2 col3 col4 _
do
[[ "$col3" == "A" && "$col4" == "B" ]] && ((count+=col2))
# Here the '[[' implies the if-clause and '&&' implies do on true condition
done<file
printf "%d\n" "$count"
您正在將'Awk'和'shell'的結構混合在一起。 – Inian
是的。我是殼牌和Linux功能的noob。我只想用if子句總結第二列。那可能嗎 ? –
請發佈一些示例數據。 –