cut and sort
In this page:
Extracting Fields with cut
cut -d DELIM -f N splits each line on DELIM and prints field number N. Multiple fields can be selected with a comma-separated list like -f1,3.
Example: Extracting Fields with cut
#!/bin/bash
echo "alice,30,engineer" | cut -d, -f2
echo "alice,30,engineer" | cut -d, -f1,3
Login to try C/C++/Java/PHP code in the editor
Extracting Characters with cut
cut -c range extracts specific character positions from each line, regardless of delimiters, which is useful for fixed-width text formats.
Example: Extracting Characters with cut
#!/bin/bash
echo "HelloWorld" | cut -c1-5
echo "HelloWorld" | cut -c6-10
Login to try C/C++/Java/PHP code in the editor
Sorting Text and Numbers
Plain sort compares lines as text, so numeric strings sort in an unexpected order (e.g. "10" before "2"). The -n flag tells sort to compare values numerically instead.
Example: Sorting Text and Numbers
#!/bin/bash
printf "10\n2\n33\n1\n" > numbers.txt
echo "lexical sort:"
sort numbers.txt
echo "numeric sort:"
sort -n numbers.txt
rm -f numbers.txt
Login to try C/C++/Java/PHP code in the editor
Sorting by a Specific Column
sort -k N sorts by the Nth field instead of the entire line, and can be combined with -n for numeric columns or a custom -t delimiter for structured data.
Example: Sorting by a Specific Column
#!/bin/bash
printf "bob 25\nalice 30\ncarl 20\n" > people.txt
echo "sorted by age (2nd field, numeric):"
sort -k2 -n people.txt
rm -f people.txt
Login to try C/C++/Java/PHP code in the editor
- Forgetting
cutsplits on a single literal delimiter character by default (tab), so-dmust be set explicitly for comma or other separators. - Assuming
sortsorts numbers correctly by default; without-nit sorts lexically, so "10" comes before "2". - Not knowing
sort -klets you sort by a specific column instead of the whole line.
cut -d, -f2extracts the second comma-separated field from each line.cut -c1-5extracts characters 1 through 5 of each line.sortsorts lexically by default;-nsorts numerically;-rreverses the order.sort -k Nsorts by the Nth whitespace- or delimiter-separated field instead of the whole line.
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first: