On this page
- When is sed the right tool, and when awk?
- How do I replace text with sed?
- How do I edit a config file in place safely?
- How do I print, delete or insert specific lines?
- How does awk split lines into fields?
- How do I filter rows and add up numbers with awk?
- Can I combine sed, awk and grep in one pipeline?
- What goes wrong most often?
- Questions
When is sed the right tool, and when awk?
Reach for sed when you want to change or cut lines as text, and for awk when each line is a record of fields you want to select, compare or add up. sed edits a stream: it reads input, applies commands like substitute or delete to each line and writes the result. awk is a small programming language built around the idea of columns, conditions and totals. Both are installed on every image.
sed --version | head -n 1
awk -W version 2>/dev/null | head -n 1Rocky and Alma use GNU awk (gawk). Ubuntu and Debian may use mawk as the default awk until you install the gawk package; every example here works with both. If your task is only finding lines, grep is simpler than either.
How do I replace text with sed?
The substitute command is s/pattern/replacement/flags. Without flags it changes the first match on each line; g changes all of them, and I (GNU sed) ignores case.
sed 's/http:/https:/' links.txt
sed 's/example.org/example.net/g' site.conf
sed 's|/var/www/old|/var/www/example.net|g' site.conf
sed -E 's/([0-9]+) MB/\1M/g' sizes.txtWhen the text contains slashes, choose another delimiter such as | so you do not have to escape every slash. With -E parentheses capture groups that you reuse as \1, \2 in the replacement, and & stands for the whole match. Without -i, sed never changes the file; it only prints the edited version, which is the safest way to try a pattern first.
How do I edit a config file in place safely?
Preview the change, then run sed with -i and a backup suffix, then test the service config before reloading.
sed -E 's/^;?memory_limit = .*/memory_limit = 256M/' /etc/php/8.3/fpm/php.ini | diff /etc/php/8.3/fpm/php.ini -
sudo sed -i.bak -E 's/^;?memory_limit = .*/memory_limit = 256M/' /etc/php/8.3/fpm/php.ini
grep -n "^memory_limit" /etc/php/8.3/fpm/php.ini
sudo php-fpm8.3 -t && sudo systemctl reload php8.3-fpmThe diff shows exactly which lines will change. -i.bak writes the new file and keeps the previous one as php.ini.bak. The paths above fit Ubuntu 24.04 with PHP 8.3; Debian 12 ships PHP 8.2 under /etc/php/8.2/, and Rocky or Alma keep a single /etc/php.ini with the service php-fpm. The PHP and PHP-FPM guide lists where each setting lives. For values that a package update may overwrite, a drop-in file is cleaner than editing the main file.
How do I print, delete or insert specific lines?
Put an address in front of a command: a line number, a range, or a pattern between slashes. With -n sed prints nothing unless told to with p.
sed -n '25,40p' app.log
sed -n '/BEGIN CERTIFICATE/,/END CERTIFICATE/p' bundle.pem
sed '/^#/d; /^$/d' /etc/fstab
sed '1d' report.csv
sed '$a # added by deploy' hosts.txt
sed '/^\[mysqld\]/a max_connections = 200' my.cnfThe examples print lines 25 to 40, extract a certificate block from a bundle, drop comments and blank lines, remove a CSV header, append a line at the end, and add a line right after a section header. i inserts before the addressed line instead of after it. Several commands are separated by semicolons. Square brackets in a pattern must be escaped, as in the last line, because they would otherwise form a character class.
How does awk split lines into fields?
awk splits each line on whitespace by default and calls the pieces $1, $2 and so on; $0 is the whole line, NF the number of fields and NR the current line number. -F sets a different separator.
awk '{print $1, $9}' /var/log/nginx/access.log | head
awk -F: '{print $1, $7}' /etc/passwd
awk '{print $NF}' file.txt
df -h | awk 'NR > 1 {print $6, $5}'In the default access log format, field 1 is the client address, field 9 the status code and field 10 the bytes sent. $NF is always the last field, however many there are. In /etc/passwd the separator is a colon, field 1 the user name and field 7 the login shell. A comma in print inserts a space between values; to control the layout exactly, use printf.
How do I filter rows and add up numbers with awk?
Put a condition before the braces to act only on matching lines, and use an END block to print results after all input is read.
awk '$9 == 500' /var/log/nginx/access.log
awk '{sum += $10} END {printf "%.1f MB\n", sum/1048576}' /var/log/nginx/access.log
awk '{n[$9]++} END {for (s in n) print n[s], s}' /var/log/nginx/access.log | sort -rn
df -h | awk 'NR > 1 && $5+0 > 80 {print "disk almost full:", $6, $5}'
awk -F: '$3 >= 1000 && $7 !~ /nologin/ {print $1}' /etc/passwdLine by line: all requests that returned 500, total traffic served in megabytes, a count of requests per status code, filesystems above 80 percent use, and real login accounts. Arrays such as n[$9] are created on first use, which makes grouping and counting very short. $5+0 turns a value like 83% into the number 83. The disk check makes a fine cron job; the cron guide shows how to schedule it.
Can I combine sed, awk and grep in one pipeline?
Yes, and that is how they are usually used: grep narrows the lines, sed tidies them, awk counts or formats.
sudo journalctl -u ssh --since today | grep "Accepted" | awk '{print $9, $11}' | sort | uniq -c
grep -h "GET /api" /var/log/nginx/access.log | sed -E 's/[?].*//' | awk '{print $7}' | sort | uniq -c | sort -rn | headThe first shows which users logged in from which addresses today (the unit is sshd on Rocky and Alma). The second ranks API endpoints with query strings removed. Build such pipelines one step at a time, checking the output after each |. Passing shell variables into awk is done with -v: awk -v min=1000 -F: '$3 >= min {print $1}' /etc/passwd. Longer logic belongs in a script; see the first bash script guide.
What goes wrong most often?
- Shell ate the dollar signs: awk programs must be in single quotes, otherwise the shell replaces
$1before awk runs. - sed -i on macOS syntax: guides written for BSD sed use
-i ''; on Linux write-ior-i.bakwith no space. - Change applied to the wrong lines: anchor patterns with
^and$, and preview without-i. - Plus or question mark has no effect in sed: add
-Efor extended expressions. - File became owned by root or lost its SELinux label:
sed -iwrites a new file; check withls -lZand runrestoreconon Rocky and Alma if needed.
Questions about Edit and report text with sed and awk
Does sed -i keep a backup automatically?
Only if you give a suffix, as in sed -i.bak. Plain -i replaces the file with no copy of the old version.
How do I replace text in many files at once?
Combine grep and sed: grep -rl old /path | xargs sed -i 's/old/new/g'. Run the grep part alone first to see which files will change.
Is awk the same on every distribution?
The core language is the same. Rocky and Alma use gawk; Ubuntu and Debian may use mawk, which lacks a few gawk extras such as strftime in older versions. Install gawk if a script needs them.
How do I use a tab as the awk field separator?
Use awk -F'\t' to read tab separated data and set OFS="\t" in a BEGIN block to write it.
Can sed edit only the first match in a file?
With GNU sed, sed '0,/old/s//new/' file changes only the first occurrence in the whole file.
More in Linux command line
- Copy files and directories with cp
- Move and rename with mv
- Create directories and empty files
- List files with ls, find your place with pwd
- Read files with cat, less and tail
- Find files with find and locate
- Search text with grep
- echo, tee and wc
- Edit files with nano
- Edit files with Vim
- Read manual pages
- Users and groups
- Ownership with chown and chgrp
- Symbolic and hard links
- Pipes, redirection and xargs