Escolar Documentos
Profissional Documentos
Cultura Documentos
|
|
|
Set Operations in the Unix Shell
v1.01 |
|
|
'----------------------------------------------------------------------------'
| Peteris Krumins (peter@catonmat.net), 2008.12.02
|
| http://www.catonmat.net - good coders code, great reuse
|
|
|
| Released under the GNU Free Document License
|
'----------------------------------------------------------------------------'
Set operations covered in this document:
---------------------------------------- Set Membership.
- Set Equality.
- Set Cardinality.
- Subset Test.
- Set Union.
- Set Intersection.
- Set Complement.
- Set Symmetric Difference.
- Power Set.
- Set Cartesian Product.
- Disjoint Set Test.
- Empty Set Test.
- Minimum.
- Maximum.
Full explanation of these operations at:
http://www.catonmat.net/blog/set-operations-in-unix-shell/
Set Membership
-------------$ grep -xc 'element' set
$ wc -l < set
$ awk 'END { print NR }' set
Subset Test
----------$ comm -23 <(sort subset | uniq) <(sort set | uniq) | head -1
# outputs something if subset is not a subset of set
# does not putput anything if subset is a subset of set
$ awk 'NR==FNR { a[$0]; next } { if !($0 in a) exit 1 }' set subset
# returns 0 if subset is a subset of set
# returns 1 if subset is not a subset of set
Set Union
--------$ cat set1 set2
# ditto
$ cat set1 set2 | sort -u # same, but assumes they are not disjoint
$ sort set1 set2 | uniq
$ sort -u set1 set2
$ awk '!a[$0]++'
# ditto
Set Intersection
---------------$ comm -12 <(sort set1) <(sort set2) # outputs insersect of set1 and set2
$ grep -xF -f set1 set2
$ sort set1 set2 | uniq -d
$ join <(sort -n A) <(sort -n B)
$ awk 'NR==FNR { a[$0]; next } $0 in a' set1 set2
Set Complement
-------------$ comm -23 <(sort set1) <(sort set2)
# outputs elements in set1 that are not in set2
$ grep -vxF -f set2 set1
# ditto
# ditto
Minimum
------$ head -1 <(sort set)
$ awk 'NR == 1 { min = $0 } $0 < min { min = $0 } END { print min }'
Maximum
------$ tail -1 <(sort set)
$ awk 'NR == 1 { max = $0 } $0 > max { max = $0 } END { print max }'
.---------------------------------------------------------------------------.
| Peteris Krumins (peter@catonmat.net), 2008.12.02
|
| http://www.catonmat.net - good coders code, great reuse
|
|
|
| Released under the GNU Free Document License
v1.01 |
|
|
| Thanks to waldner and pgas from #awk on FreeNode
|
| Power set function by Andreas: http://lysium.de/blog
|
'---------------------------------------------------------------------------'