You have a log file, a CSV export or the output of a command, and you need to extract one precise piece of information from it. On Linux, a handful of commands is enough: cut for columns, sort to sort, uniq to deduplicate, wc to count, tr to replace characters and diff to compare. This guide covers the basic uses of each one, then gives a first look at sed to replace text and at awk to sum a column.
What you will learn
- Extract columns with
cut - Sort lines with
sort - Deduplicate with
uniq - Count lines, words and bytes with
wc - Replace or delete characters with
tr - Compare two files with
diff - Discover
sedandawkto go further, up to summing a column of numbers
cut: extract columns
cut splits each line of a file on a delimiter and extracts the requested fields. It works line by line and never reorders the fields: -f6,1 returns the same result as -f1,6. One more limit to know before using it on a log: cut cannot treat several consecutive spaces as a single delimiter, which is the job of awk.
Extract one field with a delimiter
The /etc/passwd file uses : as its delimiter. To extract only the user names (first field):
cut -d: -f1 /etc/passwdrootdaemonbinbob-d:: the delimiter is:-f1: extract field number 1
Extract several fields
Separate the field numbers with a comma, with no space. The fields come out separated by the same character as the one passed to -d.
cut -d: -f1,6 /etc/passwdroot:/rootbob:/home/bobHere you get the name (field 1) and the home directory (field 6).
Extract by character position
The -c option extracts by position instead of by delimiter:
echo "abcdefgh" | cut -c1-4abcdsort: sort lines
sort sorts the lines of a file alphabetically by default. The original file is not changed: the result goes to standard output, and it is up to you to redirect it if you want to keep it. The order depends on the shell's locale, which explains why the same file does not sort identically on two machines with different settings.
sort /etc/passwdNumeric sort
By default, sort sorts as text ("9" comes after "10"). To sort numbers correctly, add -n:
sort -n file.txtReverse sort
-r reverses whatever order you got: combined with -n, it gives the descending ranking sort -rn that you find everywhere in log analysis.
sort -r file.txtSort on a given column
To sort a CSV file by its second column:
sort -t',' -k2,2 file.csv-t',': the delimiter is,-k2,2: sort on field 2, and on it alone. Written-k2without the second part,sortsorts from field 2 to the end of the line
uniq: remove duplicates
uniq removes identical consecutive lines. That is why you almost always use it after sort:
sort file.txt | uniqCount occurrences
The -c option prints the number of repetitions in front of each line:
sort file.txt | uniq -c 3 error 1 info 5 warningShow only the duplicates
-d only prints the lines that appear at least twice, once each. The opposite option, -u, only keeps the unique lines.
sort file.txt | uniq -dwc: count
wc (word count) counts lines, words and bytes (to count characters, with accents for example, use -m). Without an option, it prints the three values in this fixed order, followed by the file name. When it reads from a pipe instead of a file, the last column disappears since there is no name left to show.
wc /etc/passwd 42 64 2456 /etc/passwdThe three numbers: 42 lines, 64 words, 2456 bytes.
Count only the lines
-l actually counts newline characters: a file whose last line has none is therefore counted one short.
wc -l /etc/passwdIt is the most used option, for example to count the users of the system or the number of files in a directory:
ls /etc | wc -lCount words
Here a "word" is any sequence of characters separated by a space, a tab or a newline.
wc -w file.txttr: replace or delete characters
tr (translate) transforms or deletes characters. It always reads from standard input, through a pipe or a redirection.
Convert upper case to lower case
tr maps the two character sets position by position: A becomes a, B becomes b, and so on. Accented characters are not covered by the A-Z range.
echo "HELLO WORLD" | tr 'A-Z' 'a-z'hello worldA trap comes up often: tr does not take a file name as an argument. The command tr 'A-Z' 'a-z' notes.txt fails with the message tr: extra operand, followed by the file name in quotes. Send the file content through a pipe instead: cat notes.txt | tr 'A-Z' 'a-z'.
Delete characters
The -d option deletes every occurrence of the given character:
echo "price: 42.50 €" | tr -d ' 'price:42.50€Replace one character with another
tr replaces one character with one character, never a word with a word: for that you need sed.
echo "one;two;three" | tr ';' ','one,two,threediff: compare two files
diff shows the differences between two files, line by line. It is the basic command to know before using a tool such as Git.
diff file1.txt file2.txt2c2< banana---> bananas2c2: line 2 has changed (c = changed)<: contents of the first file>: contents of the second file
Side-by-side display
The -y option shows the two files in columns:
diff -y file1.txt file2.txtUnified display (Git style)
-u groups the differences with three lines of context on each side, deletions prefixed with - and additions with +.
diff -u file1.txt file2.txt--- file1.txt+++ file2.txt@@ -1,3 +1,3 @@ apple-banana+bananas cherryIt is the format you will find in git diff.
sed: a first look
sed (Stream Editor) transforms text on the fly. It is a very rich tool, but to start with, remember this replacement syntax:
sed 's/old/new/' file.txtThis command replaces the first occurrence of "old" with "new" on each line. Without the -i option presented below, sed writes nothing to the file: it prints the result on screen and file.txt stays unchanged.
Replace every occurrence
Add g (global) at the end of the expression to replace every occurrence on each line:
sed 's/old/new/g' file.txtChange the file directly
The -i option applies the change in the file (not only on screen), which makes it permanent:
sed -i 's/old/new/g' file.txtTo go further with sed, read the dedicated sed guide.
awk: a first look
awk is a very powerful text-processing tool, specialised in column data. Unlike cut, it splits on a run of spaces or tabs, which makes it usable directly on the output of ls -l or a system log. To start with, remember this syntax:
awk '{print $1}' file.txt$1 designates the first field (column), $2 the second, and so on. By default, the separator is the space or the tab.
This is what makes awk safer than cut on ls -l, whose columns are aligned with multiple spaces: cut -d' ' -f5 treats every space as a delimiter and can return empty fields, whereas ls -l | awk '{print $5}' prints the size of each file.
Change the separator
For a file separated by : (like /etc/passwd), the -F option sets the separator:
awk -F: '{print $1, $6}' /etc/passwdroot /rootbob /home/bobFilter lines
What comes before the braces is a condition: the block only runs on the lines that satisfy it.
awk -F: '$3 >= 1000 {print $1}' /etc/passwdThis command prints the user names whose UID (field 3) is greater than or equal to 1000: these are usually the "human" users. The nobody system account, whose UID is often 65534, also passes this filter. To exclude it, add a second condition with && (AND): awk -F: '$3 >= 1000 && $3 < 65534 {print $1}' /etc/passwd.
Do a calculation on a column
awk can also calculate. The block between braces runs on every line, so it can feed a variable that grows as the file is read. The END block runs only once, after all the lines have been read. That is where you print the result. Here is the sum of the second column of a small file separated by ;:
printf 'north;12\nsouth;30\nnorth;8\n' | awk -F';' '{ total += $2 } END { print total }'50total += $2 adds field 2 of the current line to total. This variable does not need to be declared: it is zero until you add something to it, hence the result 12 + 30 + 8 = 50. The same pattern sums a column of amounts in a real CSV file, once you adapt the separator with -F and the column number.
To go further with awk, read the dedicated awk guide.
How do you combine these commands?
The strength of these tools lies in combining them with the pipe. Each command plays a single role and passes its result to the next, which lets you build a complex processing chain without writing a script or an intermediate file. The order is decisive: uniq placed before sort will not see non-consecutive duplicates.
List the users, sorted
cut isolates the user name, sort puts the list back in the alphabetical order that /etc/passwd does not follow.
cut -d: -f1 /etc/passwd | sortThe 5 most used commands
history numbers each line, hence the $2 to get the command itself and not its number.
history | awk '{print $2}' | sort | uniq -c | sort -rn | head -n 5Count the errors in a log
Here app.log stands for an application log file of your choice: the location of system logs varies by distribution. grep -c counts the lines that contain the pattern, not the occurrences: two "error" on the same line count as one.
grep -c "error" app.logOr with grep + wc:
grep "error" app.log | wc -lTroubleshooting
These commands rarely fail loudly: most of the time they return a result, but the wrong one. That is what makes their errors hard to spot: a cut with the wrong delimiter produces plausible yet false columns. Always check the output on a few lines with head before chaining a processing step.
| Problem | Likely cause | Fix |
|---|---|---|
cut: wrong result | Wrong delimiter (-d) | Check the real delimiter of the file |
sort: numbers are sorted badly | Alphabetical sort by default | Add -n for a numeric sort |
uniq does not remove duplicates | The lines are not consecutive | Go through sort before uniq |
tr: tr: extra operand | A file name passed as an argument, or character sets without quotes | Send the content through a pipe (cat file | tr 'A-Z' 'a-z') and put the character sets in quotes |
sed -i: file corrupted | Wrong substitution | Test without -i first, then apply |
diff: no output | The files are identical | That is normal, diff says nothing when everything matches |
Put it into practice
This lab starts from a sales file in the date;region;product;amount format. You draw four facts from it with the commands of this lesson: the list of regions with cut, sort and uniq, the number of sales per region with uniq -c, the total of the amounts with awk, and a version of the file where ; becomes , with sed or tr. Each fact is saved to a file with a redirection, command > file, which the next lesson, redirections and pipes, explains in detail. The validation reads the content of your files and recomputes it from the original file.
Key points
cutextracts columns,sortsorts,uniqdeduplicates,wccounts.trreplaces or deletes characters one by one.diffcompares two files, with the-uformat for the Git style.sedandawkare more powerful, buts/old/new/gand'{print $1}'are enough to start with.awksums a column:{ total += $2 } END { print total }accumulates on every line and prints only once, at the end.- These commands make full sense when they are chained with the pipe
|.
Knowledge check
Check that the essentials of this guide stuck. The questions cover only what has just been explained here.
Knowledge check
Check what you have learned with this interactive quiz
How it works
- The timer starts when you click Start
- Multiple choice, true/false and short answer questions
- You can move between questions
- Detailed results are shown at the end
Starts the quiz and the timer
Review
(0/0)Result saved on this device. It will be sent to your account at the next sync. Sync now
Score by domain
A domain groups several guides and gets several questions, so its score is more reliable than a per-topic score, which often rests on a single question.
Summary
Strengths
No topic passed at 80% on at least two questions yet.
Weak areas
No topic below the pass mark.
Recommended next
Hints before you try again?
Continue the course: Redirections and pipes on Linux
A new full quiz with random questions
Work again only on the questions you missed