Skip to content

Linux Foundations / Find your way around Linux ยท Step 36 of 63

Lesson: cutSwitch
โ† Linux Foundations

Shell and files

cut

Learn to extract columns and character positions from lines of text with cut.

cut takes each line of its input and prints only the part you ask for. It is a quick way to pull one column out of structured text.

Cut by character position

-c selects characters, counting from 1.

$ echo "abcdefgh" | cut -c 1-3
abc
$ echo "abcdefgh" | cut -c 5
e

Ranges can be open: -c 4- means from the fourth character to the end, and -c -4 means the first four. Lists such as -c 1,3 also work. -b selects bytes instead. GNU cut before coreutils 9.11, unless your distribution patched it, treats -c like -b, so non-ASCII text can be split in the middle of a character. Newer versions count characters.

Cut by field

-f selects fields. The default separator is a tab. Use -d to name another single character.

$ cat people.txt
maya:admin:London
omar:dev:Cairo
$ cut -d ':' -f 1 people.txt
maya
omar
$ cut -d ':' -f 1,3 people.txt
maya:London
omar:Cairo

The output keeps the same separator. GNU cut lets you change it with --output-delimiter.

Things that surprise beginners

First, cut cannot reorder fields. -f 3,1 prints the same result as -f 1,3, in the order found in the line.

Second, a line that does not contain the separator is printed in full. Add -s to suppress such lines.

$ printf 'a:b\nno separator\n' | cut -d: -f2
b
no separator
$ printf 'a:b\nno separator\n' | cut -d: -f2 -s
b

Third, every single separator counts. With -d ' ', two spaces in a row create an empty field between them. For text padded with many spaces, squeeze them first with tr -s ' ', or use awk.

Combine with other tools

cut works well in pipelines. This lists the login names on your system, sorted:

$ cut -d: -f1 /etc/passwd | sort | head -n 3

Your names will differ. The streams and text lab gives you files to slice.

Try it

  1. Run date | cut -c 1-3.
  2. Print fields 1 and 7 of /etc/passwd with cut -d: -f1,7 /etc/passwd.
  3. Ask for -f7,1 and compare.
  4. Run echo "a b" | cut -d ' ' -f 2 and explain the empty line.

Check your understanding

cut

All 5 sections ยท no timer

Unlimited retries

Questions from every section are combined into one assessment. Answer them all correctly to complete the article.

Your completion saves in this browser. Sign in to sync it to your account.