Bash Cut Join and Paste
Cut, join, and paste are commands that split and combine columns of text. Cut takes fields out, paste puts columns side by side, and join merges lines that share a key.
Cut two fields out of each line
The -d flag names the colon separator, and -f picks fields 1 and 3. The middle field, the age, is dropped from every line.
printf 'ana:25:london\nbob:30:paris\n' | cut -d: -f1,3Paste two files side by side
Paste takes one line from each file for every row. A tab separates the name from the score on each row.
printf 'ana\nbob\n' > names.txt
printf '90\n80\n' > scores.txt
paste names.txt scores.txtJoin two files on a shared key
Both files are already sorted on their first field, the id. Join matches equal ids and prints the id once, then both values.
printf '1 ana\n2 bob\n3 cid\n' > names.txt
printf '1 90\n2 80\n3 70\n' > scores.txt
join names.txt scores.txtExample
printf '1 ana\n2 bob\n3 cid\n' > names.txt
printf '1 90\n2 80\n3 70\n' > scores.txt
echo "id name score"
join names.txt scores.txtKey points
- cut -d : -f 1,3: take fields 1 and 3 from colon-separated lines.
- paste: place two files side by side, one line from each per row.
- join: merge two files on a shared first field, called the key.
- join needs both files sorted on the key, or rows will be missed.
- Use cut to drop a column you do not need from joined output.
In this example, two files are created, both sorted on the id field. The echo command prints a header row for the table. Then join matches equal ids and prints each id once with its name and score.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What must be true of both files before join runs?