AI Hints
Home›Linux Tutorial›Pipes and Sorting
Linux · Lesson 48 of 120

cut

Picking out columns.

⏱ 2 min read▶ Video at 1:01:35🎓 Free
Watch this lesson in the Linux courseWatch on YouTube ↗Full Linux course

Many files are organised in columns. Our log has a date, a time, a level, a user, and a message. Often you only need one column. Cut picks it out.

cut
From the video: cut
  • Files with columns
  • You need just one
  • cut picks it out

Cutting fields

Cut dash D tells cut what separates the columns. Here, a space. Dash F picks the field number. Field four is the user. So this prints just the user names, one per line, for the first five lines of the log.

Terminal
head -n 5 logs/server.log | cut -d " " -f 4
priya
sam
sam
priya
priya

Several fields

You can ask for several fields, separated by commas. Fields two, and three, give the time and the level. Cut is perfect for CSV files too, where columns are separated by commas.

Terminal
head -n 4 logs/server.log | cut -d " " -f 2,3
09:00:23 ERROR
09:00:29 INFO
09:00:55 INFO
09:01:00 INFO

Who uses the site most?

Now put it all together. Cut out the user field. Sort the names. Count them with uniq dash C. Then sort the counts in reverse number order. Sam is our most active user. Five small commands, one real answer.

Terminal
cut -d " " -f 4 logs/server.log | sort | uniq -c | sort -rn
     18 sam
     16 alex
     15 priya
     11 jo

Summary

Cut picks columns with dash D and dash F. And cut, sort, uniq dash C, sort dash RN is a famous pipeline for counting things. Next, a few more text tools.

Key takeaways
  • cut -d ' ' -f 4
  • -f 2,3 for several
  • cut | sort | uniq -c | sort -rn
Next up: tr: Translating Characters — swap or delete characters