Skip to content
Français
Sync not enabled: your progress stays in this browser My learning
Select theme
Français

Filter and transform text on Linux

By updated

Improve this page

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 sed and awk to 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):

Terminal window
cut -d: -f1 /etc/passwd
Output (excerpt)
root
daemon
bin
bob
  • -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.

Terminal window
cut -d: -f1,6 /etc/passwd
Output (excerpt)
root:/root
bob:/home/bob

Here 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:

Terminal window
echo "abcdefgh" | cut -c1-4
Output
abcd

sort: 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.

Terminal window
sort /etc/passwd

Numeric sort

By default, sort sorts as text ("9" comes after "10"). To sort numbers correctly, add -n:

Terminal window
sort -n file.txt

Reverse sort

-r reverses whatever order you got: combined with -n, it gives the descending ranking sort -rn that you find everywhere in log analysis.

Terminal window
sort -r file.txt

Sort on a given column

To sort a CSV file by its second column:

Terminal window
sort -t',' -k2,2 file.csv
  • -t',': the delimiter is ,
  • -k2,2: sort on field 2, and on it alone. Written -k2 without the second part, sort sorts 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:

Terminal window
sort file.txt | uniq

Count occurrences

The -c option prints the number of repetitions in front of each line:

Terminal window
sort file.txt | uniq -c
Output
3 error
1 info
5 warning

Show only the duplicates

-d only prints the lines that appear at least twice, once each. The opposite option, -u, only keeps the unique lines.

Terminal window
sort file.txt | uniq -d

wc: 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.

Terminal window
wc /etc/passwd
Output
42 64 2456 /etc/passwd

The 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.

Terminal window
wc -l /etc/passwd

It is the most used option, for example to count the users of the system or the number of files in a directory:

Terminal window
ls /etc | wc -l

Count words

Here a "word" is any sequence of characters separated by a space, a tab or a newline.

Terminal window
wc -w file.txt

tr: 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.

Terminal window
echo "HELLO WORLD" | tr 'A-Z' 'a-z'
Output
hello world

A 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:

Terminal window
echo "price: 42.50 €" | tr -d ' '
Output
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.

Terminal window
echo "one;two;three" | tr ';' ','
Output
one,two,three

diff: 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.

Terminal window
diff file1.txt file2.txt
Output
2c2
< banana
---
> bananas
  • 2c2: 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:

Terminal window
diff -y file1.txt file2.txt

Unified display (Git style)

-u groups the differences with three lines of context on each side, deletions prefixed with - and additions with +.

Terminal window
diff -u file1.txt file2.txt
Output
--- file1.txt
+++ file2.txt
@@ -1,3 +1,3 @@
apple
-banana
+bananas
cherry

It 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:

Terminal window
sed 's/old/new/' file.txt

This 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:

Terminal window
sed 's/old/new/g' file.txt

Change the file directly

The -i option applies the change in the file (not only on screen), which makes it permanent:

Terminal window
sed -i 's/old/new/g' file.txt

To 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:

Terminal window
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:

Terminal window
awk -F: '{print $1, $6}' /etc/passwd
Output (excerpt)
root /root
bob /home/bob

Filter lines

What comes before the braces is a condition: the block only runs on the lines that satisfy it.

Terminal window
awk -F: '$3 >= 1000 {print $1}' /etc/passwd

This 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 ;:

Terminal window
printf 'north;12\nsouth;30\nnorth;8\n' | awk -F';' '{ total += $2 } END { print total }'
Output
50

total += $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.

Terminal window
cut -d: -f1 /etc/passwd | sort

The 5 most used commands

history numbers each line, hence the $2 to get the command itself and not its number.

Terminal window
history | awk '{print $2}' | sort | uniq -c | sort -rn | head -n 5

Count 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.

Terminal window
grep -c "error" app.log

Or with grep + wc:

Terminal window
grep "error" app.log | wc -l

Troubleshooting

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.

ProblemLikely causeFix
cut: wrong resultWrong delimiter (-d)Check the real delimiter of the file
sort: numbers are sorted badlyAlphabetical sort by defaultAdd -n for a numeric sort
uniq does not remove duplicatesThe lines are not consecutiveGo through sort before uniq
tr: tr: extra operandA file name passed as an argument, or character sets without quotesSend the content through a pipe (cat file | tr 'A-Z' 'a-z') and put the character sets in quotes
sed -i: file corruptedWrong substitutionTest without -i first, then apply
diff: no outputThe files are identicalThat 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

  • cut extracts columns, sort sorts, uniq deduplicates, wc counts.
  • tr replaces or deletes characters one by one.
  • diff compares two files, with the -u format for the Git style.
  • sed and awk are more powerful, but s/old/new/g and '{print $1}' are enough to start with.
  • awk sums 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

6 questions
6 min
70% to pass

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