使用以下数据:
$cat p1.csv
R,3
R,4
S,1
S,2
S,3
R,2
T,4
R,3
ST,4
RST,2
RSTR,4
Run Code Online (Sandbox Code Playgroud)
首先根据第2列进行排序:
$cat p1.csv | sort -t "," -k2
S,1
R,2
RST,2
S,2
R,3
R,3
S,3
R,4
RSTR,4
ST,4
T,4
Run Code Online (Sandbox Code Playgroud)
我想计算第二列的1,2,3和4的数量.有点像$ cat p1.csv | sort -t"," - k2 | uniq -f2 -c .....可以将uniq应用于一列吗?-f2未正确将uniq应用于正确的字段.输出应该采用第二列中唯一值的第一个实例并计算它们的数量.因此,必须首先在第二列上对数据进行排序.正确的输出看起来像:
1 S,1
3 R,2
3 R,3
4 R,4
Run Code Online (Sandbox Code Playgroud)
建议?
jay*_*ngh 11
你的问题不是很清楚,所以我只是将你的输出反向设计为你的输入(假设你的输出中有一个拼写错误,因为你提到计算第2列和显示的1,2和3的数字2 R,2).您可能需要更好地解释一下您的问题 -
sort -t "," -k2 < p1.csv |
awk -F, '!z[$2]++{ a[$2]=$0; } END {for (i in a) print z[i], a[i]}' |
sort -k1
Run Code Online (Sandbox Code Playgroud)
- !z[$2]++ removes the duplicates based on column 2 as awk progresses thru
each line.
- a[$2]=$0 stores the non-duplicates lines in an array
- END {..} looks at all the keys in array and pulls up values. For array a
it pulls up the first line it sees with unique column 2 (as your desired
output). For array z it pulls up number of lines seen with same column 2.
Run Code Online (Sandbox Code Playgroud)
[jaypal:~/temp] cat file
R,3
R,4
S,1
S,2
S,3
R,2
T,4
R,3
ST,4
RST,2
RSTR,4
[jaypal:~/temp] sort -t "," -k2 < t |
awk -F, '!z[$2]++{ a[$2]=$0; } END {for (i in a) print z[i], a[i]}' |
sort -k1
1 S,1
3 R,2
3 R,3
4 R,4
Run Code Online (Sandbox Code Playgroud)
要根据列查找唯一条目,可以尝试使用-u选项进行排序(但它不会为您提供计数).
从man页面:
-u, --unique
with -c, check for strict ordering;
without -c, output only the first of an equal run
Run Code Online (Sandbox Code Playgroud)
你可以试试这样的东西 -
sort -t, -k2 p1.csv | sort -u -t, -k2
Run Code Online (Sandbox Code Playgroud)
我不确定Uniq是否可以在由除空格之外的分隔符分隔的列上执行.至少在我的Mac上没有.这是手册页参考
-f num Ignore the first num fields in each input line when doing comparisons.
A field is a string of non-blank characters separated
from adjacent fields by blanks. Field numbers are one based,
i.e., the first field is field one.
Run Code Online (Sandbox Code Playgroud)
因此,如果您可以删除,分隔符并运行以下命令,则应获得所需的结果.
sort -k2 test | uniq -c -f1
Run Code Online (Sandbox Code Playgroud)
[jaypal:~/temp] cat test
R 3
R 4
S 1
S 2
S 3
R 2
T 4
R 3
ST 4
RST 2
RSTR 4
[jaypal:~/temp] sort -k2 test | uniq -c -f1
1 S 1
3 R 2
3 R 3
4 R 4
Run Code Online (Sandbox Code Playgroud)