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
eRanges 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:CairoThe 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
bThird, 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 3Your names will differ. The streams and text lab gives you files to slice.
Try it
- Run
date | cut -c 1-3. - Print fields 1 and 7 of
/etc/passwdwithcut -d: -f1,7 /etc/passwd. - Ask for
-f7,1and compare. - Run
echo "a b" | cut -d ' ' -f 2and 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.