Searching and shaping text
Logs, lists and exports are text, one record per line. A few small tools find the lines that matter, cut out the fields you need, count them and change their form, and a loop handles the cases where each line needs a decision of its own.
Finding lines with grep
Much of what computers record about themselves is plain text, one event per line. A web server writes a line for every request. A sign-in service writes a line for every attempt. When something goes wrong, the answer is usually somewhere in those lines, and the job is to find the few that matter among thousands that do not.
Here is a short sign-in log, saved as signins.log. Each
line has a time, the user, the result and the sign-in method:
2026-10-05T09:14:02Z [email protected] result=success method=password
2026-10-05T09:15:40Z [email protected] result=failure method=password
2026-10-05T09:15:58Z [email protected] result=failure method=password
2026-10-05T09:16:21Z [email protected] result=success method=passkey
2026-10-05T09:20:07Z [email protected] result=success method=passkey
2026-10-05T09:31:44Z [email protected] result=failure method=otp
2026-10-05T09:32:10Z [email protected] result=success method=password
2026-10-05T09:40:55Z [email protected] result=failure method=otp
2026-10-05T09:41:30Z [email protected] result=failure method=otp
2026-10-05T09:47:12Z [email protected] result=success method=passkey
You met grep in
Connecting commands with pipes and redirection.
It prints every line that contains a pattern:
$ grep 'result=failure' signins.log
2026-10-05T09:15:40Z [email protected] result=failure method=password
2026-10-05T09:15:58Z [email protected] result=failure method=password
2026-10-05T09:31:44Z [email protected] result=failure method=otp
2026-10-05T09:40:55Z [email protected] result=failure method=otp
2026-10-05T09:41:30Z [email protected] result=failure method=otp
Put the pattern in single quotes. Many patterns contain characters the
shell treats as special, and single quotes hand them to
grep untouched. A handful of options cover most everyday
searches:
| Option | What it does | Example on signins.log |
|---|---|---|
-c | Prints how many lines matched instead of the lines | grep -c 'result=failure' signins.log prints 5 |
-n | Puts each line's number in front of it | grep -n 'user=dev' signins.log shows lines 6, 8 and 9 |
-i | Ignores the difference between upper and lower case | grep -i 'user=ava' signins.log also finds [email protected] |
-v | Prints the lines that do not match | grep -v 'method=password' signins.log shows the six passkey and otp lines |
Options combine, so grep -ci 'user=ava' signins.log prints
2. Without -i, Ava's second sign-in would be
missed, because someone typed her address in capitals.
Patterns that match more than words
A grep pattern matches anywhere inside a line, which is
sometimes more than you meant. grep -c 'method=pass' signins.log prints
7, because it matches both password and
passkey. Patterns are written in a small language called
regular expressions, and a few of its characters
let you say precisely what you mean:
| Character | Means |
|---|---|
^ | The start of the line |
$ | The end of the line |
. | Any single character |
[abc], [0-9] | One character from the set or range |
[^ ] | One character that is not in the set, here anything but a space |
* | The thing before it, repeated any number of times, including none |
\. | A real dot, with the special meaning switched off |
The start and end markers are called anchors, and
they solve the problem above. Every line in the log ends with its
method, so grep -c 'password$' signins.log counts only
the four password sign-ins. Anchoring at the start is just as useful
with timestamps. grep '^2026-10-05T09:4' signins.log finds
the three sign-ins between 09:40 and 09:49.
The -E option turns on extended regular
expressions, which add + (one or more of the thing before
it), ? (the thing before it is optional) and
| (either side), with parentheses to group:
$ grep -cE 'method=(otp|passkey)$' signins.log
6
Finally, -o prints only the part of each line that
matched, each on its own line. This turns grep from a
line finder into a way of pulling values out of text:
$ grep -o 'user=[^ ]*' signins.log
[email protected]
[email protected]
[email protected]
...
Read user=[^ ]* as "user=, followed by any
run of characters that are not spaces". The match stops at the space
before result.
Cutting out columns
Much text comes in columns. A CSV file, short for
comma-separated values, is a table written one row per line, with
commas between the fields. Here is accounts.csv, with a
header row first:
id,name,team,logins
1,Ava Archer,Finance,42
2,Ben Okafor,Legal,7
3,Cora Diaz,Finance,115
4,Dev Diaz,Support,9
5,Eli Evans,Legal,61
cut keeps the fields you ask for. -d names
the delimiter, the character between fields, and -f lists
the field numbers, counting from 1:
$ cut -d, -f2,4 accounts.csv
name,logins
Ava Archer,42
Ben Okafor,7
Cora Diaz,115
Dev Diaz,9
Eli Evans,61
The space inside Ava Archer did not matter, because only
commas separate fields here. The header row came along too. To skip
it, tail -n +2 prints a file starting from its second
line: the + means "from line N on" rather than "the last
N lines".
This works because no field in the file contains a comma. Real CSV
files can wrap such a field in quotes, as in
"Archer, Ava", and cut would split it in
the middle. For files like that, use a program that understands CSV.
cut treats every single delimiter as a boundary, so two
spaces in a row mean an empty field between them. Text lined up with
runs of spaces, like many command outputs, is easier to split with
awk, which treats any run of spaces as one separator.
awk is a whole programming language, but this one form
is worth knowing on its own:
$ awk '{print $2}' signins.log
[email protected]
[email protected]
...
Inside the single quotes, $2 is awk's name
for the second field, not a shell variable. The single quotes keep the
shell from expanding it.
NF holds the number of fields on the line, so
$NF is always the last field, however many come before
it. That suits output whose useful part sits at the end of each line:
$ awk '{print $NF}' signins.log
method=password
method=password
...
-F chooses another separator, so
awk -F, '{print $3}' accounts.csv prints the team
column, just as cut -d, -f3 would.
Sorting and counting
sort puts lines in order, alphabetically by default.
That default is a trap with numbers, because it compares them
character by character, as text:
$ tail -n +2 accounts.csv | cut -d, -f4 | sort
115
42
61
7
9
$ tail -n +2 accounts.csv | cut -d, -f4 | sort -n
7
9
42
61
115
-n compares whole numbers by value. -r
reverses the order, so sort -rn puts the largest first.
To sort whole rows by one column, tell sort how to find
it: -t names the separator and -k the field.
Writing -k4,4 means "start and end at field 4", so
nothing after it affects the order:
$ tail -n +2 accounts.csv | sort -t, -k4,4 -rn
3,Cora Diaz,Finance,115
5,Eli Evans,Legal,61
1,Ava Archer,Finance,42
4,Dev Diaz,Support,9
2,Ben Okafor,Legal,7
uniq removes repeated lines, and uniq -c
puts a count in front of each line it keeps. The catch is that it only
compares each line with the one directly before it. Repeats that are
not next to each other count separately, so sort first to bring them
together:
$ tail -n +2 accounts.csv | cut -d, -f3 | sort | uniq -c
2 Finance
2 Legal
1 Support
The counts are padded with spaces on the left. Ubuntu pads them to a
wider column than macOS does, so the exact spacing in your terminal may
differ from the example output here. When you need the second column of
that output, awk '{print $2}' handles the padding for you.
Changing text with tr and sed
Sometimes the text is right but its form is not. tr,
short for translate, swaps one set of characters for another. It reads
only from its input, so give it a pipe or a <
redirect:
$ grep -o 'user=[^ ]*' signins.log | tr 'A-Z' 'a-z' | sort | uniq -c
2 [email protected]
3 [email protected]
2 [email protected]
3 [email protected]
Without tr, [email protected] would be counted
as a different person. Two more forms come up often.
tr -d deletes characters, and tr -s ' '
squeezes each run of spaces into one.
tr -d earns its place with files made on Windows. Linux
and macOS end each line with one invisible character, the newline.
Windows ends each line with two: a carriage return,
written \r, and then the newline. The carriage return
does not show when you print the file, but it is there before every
line ending, so a pattern such as ',active$' finds
nothing: the line ends in active followed by
\r. tr -d '\r' < export.csv > clean.csv
removes every carriage return and leaves ordinary lines.
sed, the stream editor, changes text by pattern. Its most
common use is substitution: s/old/new/ replaces the first
match of old on each line with new. The
pattern is a regular expression, as in grep:
$ grep -o 'user=[^ ]*' signins.log | sed 's/user=//' | head -n 2
[email protected]
[email protected]
Replacing with nothing deletes the match. Add g after the
last slash, as in s/a/b/g, to replace every match on the
line rather than only the first.
sed does not change the file it reads. It prints the
changed text, and you can save it with a redirect, such as
sed 's/@example\.com/@example.org/' signins.log >
renamed.log. Never redirect into the file you are reading,
as in sed '...' signins.log > signins.log. The shell
empties the file for writing before sed reads a single
line, and the contents are lost. sed has an option for
editing a file in place, but it is written differently on Ubuntu and
macOS, so this course writes to a new file instead.
Building a pipeline step by step
Each of these tools does one small thing, and their power comes from connecting them. Suppose you want to know who failed to sign in most often. Nobody writes the whole command at once. Start with one stage, look at its output, and add the next stage only when the output is what you expect.
First, find the failures with grep 'result=failure': five lines. Next, keep only the user from each line with grep -o and remove the user= label with sed, which leaves five addresses. Then sort | uniq -c brings each user's lines together and counts them, and sort -rn puts the largest count first:
grep 'result=failure'
- Lines out
- 5 of 10
2026-10-05T09:15:40Z [email protected] result=failure method=password
2026-10-05T09:15:58Z [email protected] result=failure method=password
2026-10-05T09:31:44Z [email protected] result=failure method=otp
2026-10-05T09:40:55Z [email protected] result=failure method=otp
2026-10-05T09:41:30Z [email protected] result=failure method=otp
grep -o 'user=[^ ]*' | sed 's/user=//'
- Lines out
- 5
When a stage surprises you, remove the stages after it and look at what it actually produced.
$ grep 'result=failure' signins.log | grep -o 'user=[^ ]*' | sed 's/user=//' | sort | uniq -c | sort -rn
3 [email protected]
2 [email protected]Adding | head -n 1 would keep only the top line. On ten lines you could have counted by eye, but the same pipeline answers the question just as quickly for ten million. When a stage surprises you, remove the stages after it and look at what it actually produced.
Loops over words and lines
A pipeline treats a file as one stream of lines, and every stage does the same thing to every line. Sometimes you want to run a few commands once for each item instead: once per user, once per file, or once per line with a decision about each one. That is a loop.
A for loop runs the lines between do and done once for each word in a list, with a variable holding the current word:
$ for user in ava ben dev; do
> echo "$user: $(grep -c "user=$user@" signins.log)"
> done
ava: 1
ben: 3
dev: 3The > at the start of the middle lines is the shell's prompt for "keep typing": it knows the loop is not finished until done. Ava's count is 1 because the pattern is case-sensitive and her second sign-in was typed as AVA; grep -ci would find both. The list can also come from a file name pattern like those in Finding your way around files and directories. The shell expands *.log into every matching name before the loop starts:
for file in *.log; do
echo "$file: $(wc -l < "$file") lines"
doneTo work through a file one line at a time, use a while loop with read, which you met in Variables, quoting and the environment:
while read -r time user result method; do
echo "$user used $method"
done < signins.logdone < signins.log feeds the file to the whole loop. Each time round, read takes one line, splits it at spaces, and puts the words into the variables in order; if a line has more words than variables, the last variable receives the rest of the line. At the end of the file, read fails, and that is what stops the while loop. You may see for line in $(cat signins.log) suggested instead. It does not do what it seems to: word splitting breaks the file at every space, so the loop sees one word at a time, not one line.
A loop can count and decide. Bash adds whole numbers with $(( )), where names are read as variables even without a $, and if runs lines only when a test succeeds:
failures=0
while read -r time user result method; do
if [[ "$result" == "result=failure" ]]; then
failures=$((failures + 1))
fi
done < signins.log
echo "$failures"It prints 5, the same as grep -c 'result=failure'. if runs the command after it, here a test, and when that succeeds it runs the lines after then; fi, "if" backwards, ends the block. [[ "$result" == "result=failure" ]] succeeds when the two pieces of text are the same, and != tests that they differ. The spaces just inside the brackets are required, because [[ and ]] are separate words to the shell. failures=0 comes before the loop and echo after it, so the count is neither reset nor printed on every line.
For a file whose fields are separated by commas, tell read where to split. IFS holds the characters read splits at, and writing IFS=, in front of it sets that for this one command, like TZ=UTC date. This adds up the Finance logins in accounts.csv, which no counting stage could do:
total=0
while IFS=, read -r id name team logins; do
if [[ "$team" == "Finance" ]]; then
total=$((total + logins))
fi
done < accounts.csv
echo "$total"It prints 157, Ava's 42 and Cora's 115. The header row's team is team, so the test skips it. Bash arithmetic uses whole numbers only, so $(( 7 / 2 )) is 3.
Pipelines and loops overlap, and the choice is usually clear. sort | uniq -c counts lines, and a pipeline of small tools stays short and fast even on millions of lines. A loop costs more lines and runs more slowly, but it is the natural fit when each line needs a decision across several fields, a running total of numbers, or a few commands of its own.
Check your understanding
Try these questions before moving on. If an answer isn't right, use the feedback and try again.
Try it in the Lab
- Search, cut and count a staff list to find the busiest departmentSearch your own staff list with grep and regular expressions, cut out columns, sort and count them, check a count with a loop, then build a pipeline that finds the department with the most active people.