Text Processing: awk & sed — Terminal

awk splits each line into fields (columns): $1, $2 and so on, with $0 for the whole line. awk '{print $2}' app.log takes column 2. awk '/ERROR/ {print $3}'…

Picture a stack of shopping receipts, and all you need is the totals. You could copy one column from every receipt, or replace one word on all of them at the same time. In the terminal, each receipt is one line of text in a file, and there is a tool for each of those two jobs. awk takes one column from every line, for example only the total column. sed runs "find and replace" like in a text editor, but on every line with one command. Both are classic tools for working on text line by line, directly from the terminal, without opening an editor.

The example file: app.log

Every example in this lesson uses app.log, a server log (a file where the server records events, one line per event) with 4 lines:

2024-01-15 ERROR user.service Connection failed
2024-01-15 INFO auth.service Login success
2024-01-16 ERROR db.service Timeout
2024-01-16 WARN cache.service Memory high

awk: take a column

awk reads a file line by line, then splits each line at the spaces into fields (columns). The first field is $1, the second $2, and so on. $0 is the whole line. This is not the shell's $1 that holds an argument: inside the code you write for awk, $1 is the first field. The first line splits like this:

$1 $2 $3 $4 $5
2024-01-15 ERROR user.service Connection failed

This command shows field 2 of every line:

$ awk '{print $2}' app.log
ERROR
INFO
ERROR
WARN

If you only want certain lines, write a pattern (text that is matched against each line) in front of the curly braces:

$ awk '/ERROR/ {print $3}' app.log
user.service
db.service

/ERROR/ means "only lines containing ERROR". The result is the same as grep ERROR app.log | awk '{print $3}': filter first, then take the column.

For text whose columns are separated by commas (the CSV format), change the separator with -F:

$ echo "Alice,30,London" | awk -F',' '{print $2}'
30

Be careful: -F',' cuts at every comma, including a comma inside quotes. In the line "Alice, Jr.",30, awk sees three columns, so $2 holds Jr." (with a space at the start), not 30. For CSV files whose values can contain commas, use a tool that understands CSV quotes, such as Miller (mlr) or csvkit (csvcut).

sed: find and replace

sed (short for stream editor) runs a command on every line. The command you'll use most is s (substitute, which means replace), in the form s/find/replace/.

Before you look at the output, guess: the line 2024-01-15 ERROR user.service Connection failed goes through sed 's/-/./', which replaces - with .. Is the result 2024.01.15 or 2024.01-15?

$ sed 's/-/./' app.log
2024.01-15 ERROR user.service Connection failed
2024.01-15 INFO auth.service Login success
2024.01-16 ERROR db.service Timeout
2024.01-16 WARN cache.service Memory high
$ sed 's/-/./g' app.log
2024.01.15 ERROR user.service Connection failed
2024.01.15 INFO auth.service Login success
2024.01.16 ERROR db.service Timeout
2024.01.16 WARN cache.service Memory high

Without g, sed only replaces the first match on each line, so the date becomes 2024.01-15. The g (global) flag replaces every match.

Other sed commands you'll use often:

sed 's/2024-01-15/REDACTED/' app.log   # replace that date with REDACTED
sed '/INFO/d' app.log                  # delete the lines containing INFO
sed -n '2,3p' app.log                  # print only lines 2 to 3

Join them with pipes: sort and uniq

The command below counts how many times each level (ERROR, INFO, WARN) appears in column 2:

$ awk '{print $2}' app.log | sort | uniq -c
      2 ERROR
      1 INFO
      1 WARN

From the terminal to JavaScript

In the exercise, you rewrite how awk, grep and sed work in JavaScript, with the same 4 log lines:

In the terminal In JavaScript, for each line
awk '{print $2}' line.split(" ")[1] (indexes start at 0, awk columns start at 1)
grep ERROR then awk '{print $3}' filter with line.includes("ERROR") first, then take the column
sed 's/2024-01-15/REDACTED/g' line.split("2024-01-15").join("REDACTED")

split(text).join(replacement) replaces every match, exactly like the g flag.

⚠️ Why did awk or sed print something else?

TL;DR: awk splits each line into fields (columns): $1, $2 and so on, with $0 for the whole line. awk '{print $2}' app.log takes column 2. awk '/ERROR/ {print $3}' takes column 3, only from lines containing ERROR. -F',' changes the column separator to a comma, for CSV. A missing field is empty. sed 's/find/replace/' replaces the first match on each line, and with g at the end, every match. sed '/INFO/d' deletes the lines containing INFO. sed only changes the file when given -i. Without -i, sed only shows the result. sort | uniq -c counts duplicate lines. sort must come first, because uniq only removes duplicates that are next to each other. Always wrap the code for awk and sed, like '{print $2}', in single quotes.

⚡ awk: take a column

Write:

awk '{print $2}' app.log

Meaning: awk splits each line at the spaces into fields (columns): $1, $2, and so on. For the example file app.log, this prints column 2 of every line: ERROR, INFO, ERROR, WARN. Use single quotes so the shell does not replace $2.

⚡ Only certain lines

Write:

awk '/ERROR/ {print $3}' app.log

Meaning: /ERROR/ in front of the curly braces means only lines containing ERROR are used. The result is user.service and db.service: column 3 of the two ERROR lines.

⚡ sed: find and replace

Write:

sed 's/-/./g' app.log
Guess first: s/-/./g replaces - with .. Without the g at the end, what does the date 2024-01-15 become?

2024.01-15. Without g, sed only replaces the first match on each line. g (global) replaces them all.

Meaning: sed only shows the result on the screen. The file changes only when you add -i.

⚡ Count the duplicates

Write:

awk '{print $2}' app.log | sort | uniq -c

Meaning: awk takes column 2, sort puts identical lines next to each other, then uniq -c joins those duplicate lines and counts them: 2 ERROR, 1 INFO, 1 WARN.

What you will learn