cut, paste and join — Working with Columns
Asha's harvest file has four columns, but today she only needs the crop names. Tomorrow she'll want to line up two lists side by side, and after that match each picker with their garden plot. These are column jobs, and three tools cover them.
The rule
cut slices columns; paste glues lines; join matches on a key.
cut keeps only the columns you ask for. Use -d to give the separator and -f for the field numbers:
$ cut -d, -f2 harvest.csv
crop
tomato
basil
tomato
chilli
tomato
basil
$ cut -d, -f2,4 harvest.csv # crop and picker
$ cut -d, -f2- harvest.csv # field 2 to the end
$ cut -c1-10 harvest.csv # characters 1 to 10: the dateWithout -d, cut assumes the columns are separated by tabs.
paste glues files together line by line: line 1 with line 1, line 2 with line 2, and so on. Tabs go in between by default:
$ paste names.txt plots.txt
asha plot-1
ravi plot-2
meera plot-3
$ paste -d, names.txt plots.txt # comma instead of tab
$ paste -sd, names.txt # one file onto one line
asha,ravi,meerajoin matches lines from two files that share a key field, a bit like a database join. Both files must be sorted on that key. Here pickers.csv holds asha,plot-1, meera,plot-3 and ravi,plot-2, and totals.csv holds each picker's total kilograms:
$ join -t, pickers.csv totals.csv
asha,plot-1,4.9
meera,plot-3,4.1
ravi,plot-2,2.4-t, sets the separator. By default the key is the first field of each file.
(A related tool, split, does the opposite of gluing: split -l 1000 big.csv part- cuts a big file into pieces of 1000 lines each.)