← Back to Bash Course | Chapter 10: Text Processing Tools | Lesson 7 of 12

cut and sort

cut pulls out specific columns or characters from each line, and sort rearranges lines into order.

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

bash
#!/bin/bash
echo "alice,30,engineer" | cut -d, -f2
echo "alice,30,engineer" | cut -d, -f1,3

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

bash
#!/bin/bash
echo "HelloWorld" | cut -c1-5
echo "HelloWorld" | cut -c6-10

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

bash
#!/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

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

bash
#!/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
Common Mistakes
  1. Forgetting cut splits on a single literal delimiter character by default (tab), so -d must be set explicitly for comma or other separators.
  2. Assuming sort sorts numbers correctly by default; without -n it sorts lexically, so "10" comes before "2".
  3. Not knowing sort -k lets you sort by a specific column instead of the whole line.
Chapter Summary
  • cut -d, -f2 extracts the second comma-separated field from each line.
  • cut -c1-5 extracts characters 1 through 5 of each line.
  • sort sorts lexically by default; -n sorts numerically; -r reverses the order.
  • sort -k N sorts 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.