Ravindra BagaleCourses & study guides मराठी Track your progress

AWS Cloud

Linux sed Command Tutorial: Find and Replace, Delete Lines and Edit Files In Place

sed is the stream editor. It reads text line by line, changes it with simple commands and prints the result, without opening an editor. You use it to find and replace, delete lines, print a range, add lines and edit config files from scripts on hundreds of servers.

In this chapter

  • Find and replace with s///
  • Edit files in place safely with -i and backups
  • Pick lines with addresses and ranges
  • Delete, print, insert, append and change lines
  • Use -E groups and back-references
  • Run many commands and safe config edits

1. An everyday example: fixing a wedding card list

Anil typed 300 guest names for wedding cards. Later he found: 'Pune' was typed as 'Poona' everywhere, he must delete every line marked 'cancelled', print only guests 50 to 80 for his sister, add 'Shri' before some names, and he wants a backup of the original list in case he makes a mistake.

Replace Poona with Pune = sed 's/Poona/Pune/g'. Delete cancelled = sed '/cancelled/d'. Guests 50-80 = sed -n '50,80p'. Add Shri = sed 's/^/Shri /'. Backup = sed -i.bak.

How sed works on each lineRead one line into the pattern spaceCheck each command's address: does this line match?Run the command (s, d, p, i, a, c)Print the pattern space (unless -n or d)Go to the next lineWith -i, write the result back to the file
Without -i, an ordinary substitution writes its result to standard output and leaves the input file alone.

2. Find and replace with s///

Read a sed substitution in pieces. In s/FOO/BAR/, FOO is the pattern, BAR is the replacement, and slashes separate the fields. By default the first match on each matching line changes. With a trailing g, every nonoverlapping match on that line changes. For the input FOO FOO, the first command writes BAR FOO to output and the second writes BAR BAR.

Preview an intended edit on a scratch copy before using -i. Read both a matching line and a deliberately nonmatching line in the preview. The source file still has the original text after a basic preview substitution. When using the backed-up in-place example, compare the result with the backup to prove only the expected lines changed.

Changing a hostname, version or path across a file by hand is slow and error-prone.

sed 's/old/new/' replaces the first match on each line. Flags: g all matches, i ignore case (GNU), 2 only the 2nd match, p print the changed line. Any character can be the separator: s#/old/path#/new/path# avoids escaping slashes. & in the replacement means 'the whole match'. Use double quotes only when you want a shell variable inside.

FormDoes
s/a/b/First a on each line
s/a/b/gEvery a
s/a/b/2Only the 2nd a
s/a/b/giEvery a, any case
s#/x#/y#Other separator
s/.*/[&]/& = whole match
  1. Replace the first match per line.
echo 'Poona to Poona' | sed 's/Poona/Pune/'

Output:

Pune to Poona

Only the first one changed.

  1. Replace all.
echo 'Poona to Poona' | sed 's/Poona/Pune/g'

Output:

Pune to Pune

g = global.

  1. Change a path with another separator.
echo 'root /var/www/old;' | sed 's#/var/www/old#/srv/shop#'

Output:

root /srv/shop;

No need to escape every /.

  1. Use a shell variable.
V=2.4.1; sed "s/^version=.*/version=$V/" app.ini

Output:

name=shop
version=2.4.1

Double quotes let $V expand.

  1. Wrap each match with &.
echo 'order 8812 and 8813' | sed -E 's/[0-9]+/#&/g'

Output:

order #8812 and #8813

& puts the matched number back.

  1. Only print lines that changed.
sed -n 's/ERROR/E!/p' app.log | head -2

Output:

10:12:44 E! payment timeout
10:15:02 E! db refused

-n stops normal printing; p prints changed ones.

  1. Remove trailing spaces and Windows CR.
sed -i 's/[[:space:]]*$//' deploy.sh && cat -A deploy.sh | head -1

Output:

#!/bin/bash$

[[:space:]] also covers \r.

3. Edit files in place with -i (and keep a backup)

Scripts and automation must change real files, not just print. One wrong sed -i can break a server, so backups matter.

sed -i edits the file. sed -i.bak keeps the original as file.bak. On macOS (BSD sed) you must write sed -i '' for no backup. Always dry-run first without -i, or show a diff: sed 's/a/b/' f | diff f -. -i replaces the file, so it can change owner or break symlinks; use --follow-symlinks when the target is a link.

  1. Dry run first.
sed 's/^Port 22$/Port 2222/' /etc/ssh/sshd_config | diff /etc/ssh/sshd_config -

Output:

17c17
< Port 22
---
> Port 2222

Shows exactly what will change.

  1. Edit with a backup.
sudo sed -i.bak 's/^Port 22$/Port 2222/' /etc/ssh/sshd_config && ls /etc/ssh/sshd_config*

Output:

/etc/ssh/sshd_config  /etc/ssh/sshd_config.bak

The original is safe in .bak.

  1. Validate before restart.
sudo sshd -t && sudo systemctl reload sshd

Output:

(no output)

Never restart SSH without testing the config.

  1. Edit many files at once.
sed -i 's/old-db.local/db.prod.local/g' config/*.yml && grep -l db.prod.local config/*.yml

Output:

config/app.yml
config/worker.yml

Every .yml file is updated.

  1. Restore from backup.
sudo mv /etc/ssh/sshd_config.bak /etc/ssh/sshd_config

Output:

(no output)

Undo is one move.

4. Addresses: choose which lines

Often you want to change only line 5, only lines in a section, or only lines that contain a word.

Put an address before a command. N a line number, $ the last line, /re/ lines matching a regex, N,M a range, /start/,/end/ a regex range, N~S every S-th line from N (GNU), addr! all lines except addr. Example: sed '/^\[db\]/,/^\[/s/host=.*/host=10.0.0.9/' edits host only inside the [db] section.

AddressSelects
5Line 5
$Last line
2,8Lines 2 to 8
/ERROR/Lines with ERROR
/start/,/end/From start to end match
1~2Odd lines
/^#/!Lines NOT starting with #
  1. Print lines 20 to 25.
sed -n '20,25p' app.log

Output:

(6 lines)

-n plus p prints only the range.

  1. Print the last line.
sed -n '$p' app.log

Output:

10:59:59 INFO shutdown

$ is the last line.

  1. Change only inside a section.
sed '/^\[db\]/,/^\[/s/^host=.*/host=10.0.0.9/' app.ini

Output:

[web]
host=0.0.0.0
[db]
host=10.0.0.9

The web host is untouched.

  1. Logs between two times.
sed -n '/^10:00/,/^10:05/p' app.log | head -3

Output:

10:00:01 INFO start
10:00:02 GET /
10:01:10 GET /cart

A regex range is great for time windows.

  1. Replace on every line except comments.
sed '/^#/!s/8080/9090/' app.conf

Output:

# default 8080
port=9090

! negates the address.

  1. Every 2nd line.
seq 1 6 | sed -n '0~2p'

Output:

2
4
6

first~step (GNU sed).

5. Delete, print, insert, append and change lines

Besides replace, you need to remove lines, add a new setting after a line, or replace a whole line.

d deletes, p prints, i\ text inserts before, a\ text appends after, c\ text changes the whole line, = prints the line number, q quits (stop early, great for big files), r file reads a file in, w file writes matching lines out. GNU sed allows the one-line forms: '3i text', '/re/a text'.

  1. Delete comments and blank lines.
sed '/^#/d; /^$/d' nginx.conf | head -3

Output:

user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;

Two commands separated by ;.

  1. Delete the first line (header).
sed '1d' sales.csv | head -2

Output:

2026-10-01,Pune,4500
2026-10-01,Nashik,3200

Same as tail -n +2.

  1. Insert a line before line 1.
sed '1i # Managed by Ansible - do not edit' app.conf | head -2

Output:

# Managed by Ansible - do not edit
port=8080

i inserts before.

  1. Append a setting after a match.
sed '/^\[mysqld\]/a max_connections=500' my.cnf

Output:

[mysqld]
max_connections=500
datadir=/var/lib/mysql

A adds after the matched line.

  1. Change a whole line.
sed '/^SELINUX=/c SELINUX=permissive' /etc/selinux/config | grep ^SELINUX=

Output:

SELINUX=permissive

c replaces the full line, whatever it was.

  1. Stop early on a huge file.
sed '10q' huge.log | wc -l

Output:

10

q quits after line 10. Like head, but inside sed.

  1. Write matching lines to another file.
sed -n '/ERROR/w errors.txt' app.log && wc -l errors.txt

Output:

27 errors.txt

w saves matches without a pipe.

6. Extended regex, groups and back-references

You need to swap parts, reformat dates or keep part of a match while changing the rest.

sed -E enables extended regex (+ ? {} | ( ) without backslashes). ( ) captures a group, and \1 \2 put the groups back in the replacement. GNU sed also has \U uppercase, \L lowercase and \E end case change in the replacement.

  1. Swap first and last name.
echo 'Bagale Ravindra' | sed -E 's/(\w+) (\w+)/\2 \1/'

Output:

Ravindra Bagale

\1 is the first group, \2 the second.

  1. Reformat a date.
echo '2026-10-25' | sed -E 's/([0-9]{4})-([0-9]{2})-([0-9]{2})/\3\/\2\/\1/'

Output:

25/10/2026

Three groups, written back in a new order.

  1. Mask card numbers in logs.
echo 'card=4111111111111111 ok' | sed -E 's/([0-9]{4})[0-9]{8}([0-9]{4})/\1********\2/'

Output:

card=4111********1111 ok

Keeps first and last 4 digits.

  1. Uppercase a key name.
echo 'db_host=10.0.0.9' | sed -E 's/^([a-z_]+)=/\U\1\E=/'

Output:

DB_HOST=10.0.0.9

\U ... \E (GNU sed).

  1. Pull a value out.
sed -nE 's/.*version="([^"]+)".*/\1/p' package.xml

Output:

3.2.0

Print only the captured version.

7. Many commands, scripts and safe habits

Real edits need several steps in one pass, and must be safe to run again and again (idempotent).

Join commands with ; or -e, or use { } to group commands under one address. Save long edits in a file and run sed -f edits.sed. To make edits idempotent, match the full current line (^key=.*) so a second run changes nothing. For structured files (JSON, YAML, XML) prefer jq, yq or xmlstarlet; for big configs prefer Ansible lineinfile.

  1. Two edits in one run.
sed -e 's/dev/prod/' -e '/debug/d' app.conf

Output:

env=prod
port=8080

-e can repeat.

  1. Group commands under one address.
sed '/^\[db\]/,/^\[/{s/^user=.*/user=app/; s/^port=.*/port=5432/}' app.ini | sed -n '/\[db\]/,$p'

Output:

[db]
user=app
port=5432

{ } applies both only inside [db].

  1. A sed script file.
printf 's/Poona/Pune/g\n/cancelled/d\n' > fix.sed && sed -f fix.sed guests.txt | wc -l

Output:

288

12 cancelled lines removed and the city fixed.

  1. Idempotent set-or-add.
grep -q '^MaxAuthTries' /etc/ssh/sshd_config && sudo sed -i 's/^MaxAuthTries.*/MaxAuthTries 3/' /etc/ssh/sshd_config || echo 'MaxAuthTries 3' | sudo tee -a /etc/ssh/sshd_config

Output:

(no output, or MaxAuthTries 3)

Runs safely many times.

  1. Number every line (= command).
sed -n '/ERROR/=' app.log | head -3

Output:

57
90
131

= prints the line number of each match.

8. Real examples from many industries

The same Linux skill shows up in every kind of company. Seeing it in many places helps you remember it.

Each row is a made-up team. It shows who uses this and how.

Team and cityHow they use itCommand
Sanjay, Infra automation, PuneHardens SSH on 400 servers with backupssed -i.bak 's/^#\?PermitRootLogin.*/PermitRootLogin no/' /etc/ssh/sshd_config
Elena, CI team, WarsawBumps the version in files during releasesed -i "s/^version=.*/version=$TAG/" gradle.properties
Tunde, fintech, LagosMasks card numbers before shipping logssed -E 's/[0-9]{12}([0-9]{4})/XXXX\1/g'
Ayesha, analytics, KarachiCleans CSV exports: strips header and CRsed '1d; s/\r$//' export.csv
Liam, SRE, DublinPulls a 5-minute window from a big logsed -n '/^10:00/,/^10:05/p' app.log
Neha, Docker builds, BengaluruSwitches apt mirrors in a Dockerfile RUN stepsed -i 's#http://archive#http://in.archive#g' /etc/apt/sources.list

9. Common errors and how to fix them

Everyone hits these errors. Knowing the cause saves hours.

Read the exact message first. Then match it to a row below.

Error you seeWhy it happensHow to fix
sed: -e expression #1, char 9: unterminated `s' commandMissing a / or the separator appears inside the textCount separators or use another one like #.
sed 's#/a/b#/c/d#' f
sed: -e expression #1, char 5: unknown option to `s'A / inside a path ends the command earlyUse # or | as separator.
sed 's|/var/www|/srv|' f
sed: can't read file.txt: No such file or directoryWrong file name or pathCheck with ls.
ls -l file.txt
sed: couldn't open temporary file ./sedXyz: Permission denied-i needs write permission on the folderUse sudo or edit where you can write.
sudo sed -i 's/a/b/' /etc/app.conf
sed: 1: "file": invalid command code f (macOS)BSD sed -i needs a suffix argumentUse -i '' on macOS, or install gnu-sed.
sed -i '' 's/a/b/' file
Variable not replaced: shows $V literallySingle quotes stop the shell expanding $VUse double quotes around the expression.
sed "s/x/$V/" f
Replacement broke because the value has / or &/ and & are special in the replacementEscape them or use another separator.
sed "s|x|${V//&/\\&}|" f
sed: invalid reference \1 on `s' command's RHSYou used \1 without a ( ) group (or forgot -E)Add -E with ( ) or use \( \) in basic mode.
sed -E 's/(a)b/\1/' f
Symlinked config replaced by a plain file after -i-i writes a new file instead of the linkUse --follow-symlinks.
sed -i --follow-symlinks 's/a/b/' link.conf
sed changed nothingPattern does not match (case, spaces, \r)Test with grep first, check cat -A.
grep -n 'Port' f | cat -A

10. Troubleshooting step by step

When a sed edit does not do what you expect, test it in small steps without -i.

Go top to bottom. Stop at the first step that shows the problem.

  1. Confirm the line exists and see hidden characters.
grep -n '^Port' /etc/ssh/sshd_config | cat -A
  1. Run without -i and diff the result.
sed 's/^Port 22/Port 2222/' /etc/ssh/sshd_config | diff /etc/ssh/sshd_config -
  1. Check which sed you have.
sed --version | head -1
  1. Check quotes: print the final expression.
echo "s/^version=.*/version=$V/"
  1. After -i, check the file and its owner.
ls -l /etc/ssh/sshd_config*
  1. Validate the service config before reload.
sudo sshd -t; sudo nginx -t

11. Lab 1: Clean up a guest list

Practise replace, delete, print ranges and backups on a safe file.

A full hands-on lab. Run every step on a test Linux machine (an EC2 instance, a VM, or WSL).

  1. Create the list.
mkdir -p ~/lab10 && cd ~/lab10 && for i in $(seq 1 100); do echo "$i,Guest$i,Poona$([ $((i%10)) -eq 0 ] && echo ',cancelled')"; done > guests.txt; head -2 guests.txt

Output:

1,Guest1,Poona
2,Guest2,Poona
  1. Fix the city (dry run).
sed 's/Poona/Pune/g' guests.txt | head -2

Output:

1,Guest1,Pune
2,Guest2,Pune
  1. Apply with a backup.
sed -i.bak 's/Poona/Pune/g' guests.txt && ls guests*

Output:

guests.txt  guests.txt.bak
  1. Delete cancelled guests.
sed -i '/cancelled/d' guests.txt && wc -l < guests.txt

Output:

90
  1. Print guests 50 to 52.
sed -n '50,52p' guests.txt

Output:

55,Guest55,Pune
56,Guest56,Pune
57,Guest57,Pune
  1. Add a title line at the top.
sed -i '1i id,name,city' guests.txt && head -1 guests.txt

Output:

id,name,city

12. Lab 2: Safe, repeatable config edits

Edit an ini file by section, make the edit idempotent and roll back.

A full hands-on lab. Run every step on a test Linux machine (an EC2 instance, a VM, or WSL).

  1. Create an ini file.
cd ~/lab10 && printf '[web]\nhost=0.0.0.0\nport=80\n[db]\nhost=localhost\nport=3306\n' > app.ini

Output:

(no output)
  1. Change only the db host.
sed -i.orig '/^\[db\]/,/^\[/s/^host=.*/host=10.0.0.9/' app.ini && cat app.ini

Output:

[web]
host=0.0.0.0
port=80
[db]
host=10.0.0.9
port=3306
  1. Run it again: nothing changes.
sed '/^\[db\]/,/^\[/s/^host=.*/host=10.0.0.9/' app.ini | diff app.ini - && echo idempotent

Output:

idempotent
  1. Append a setting under [db].
sed -i '/^\[db\]/a pool=20' app.ini && sed -n '/\[db\]/,$p' app.ini

Output:

[db]
pool=20
host=10.0.0.9
port=3306
  1. Roll back.
mv app.ini.orig app.ini && grep host app.ini

Output:

host=0.0.0.0
host=localhost

Ravindra Bagale's Tip

Never run sed -i on a production config without first running the same command without -i (or piping it into diff), and always keep a backup with -i.bak. Then validate (nginx -t, sshd -t) before you reload.

13. Frequently asked questions

Q. Does sed change my file?

Only with -i. Otherwise it prints the result and the file stays the same.

Q. What does the g at the end mean?

Global: replace every match on the line, not just the first.

Q. Why use # instead of /?

When the text has slashes (paths, URLs), another separator avoids escaping.

Q. sed or awk?

sed for line edits and replace. awk for columns, maths and reports.

Q. Can sed edit JSON or YAML?

It can for simple lines, but it is risky. Use jq or yq for structured data.

Q. Why does sed -i fail on macOS?

BSD sed needs a backup suffix: sed -i '' 's/a/b/' file.

Q. How do I print one line, say line 42?

sed -n '42p' file.

Q. How do I delete the last line?

sed '$d' file.

14. Interview questions and answers

Beginner level

Q. How do you replace all 'foo' with 'bar' in a file and save it?

sed -i 's/foo/bar/g' file (add .bak for a backup).

Q. How do you print lines 10 to 20?

sed -n '10,20p' file.

Q. How do you delete blank lines?

sed '/^$/d' file.

Q. What does -n do in sed?

Stops automatic printing, so only p prints.

Mid level level

Q. Replace only on lines that contain 'prod'.

sed '/prod/s/a/b/g' file.

Q. Add a line after a match.

sed '/^\[mysqld\]/a max_connections=500' my.cnf.

Q. Swap two words with groups.

sed -E 's/(\w+) (\w+)/\2 \1/'.

Q. How do you use a shell variable in sed?

Use double quotes: sed "s/x/$V/"; watch for / and & in the value.

Senior level

Q. Why is sed -i not truly in-place and why does it matter?

It writes a temp file and renames it: new inode, may reset ownership/SELinux context, breaks hard links and replaces symlinks (unless --follow-symlinks). Open file handles still see the old file.

Q. How do you make a sed config change idempotent in automation?

Match the full current line (^key=.*) and replace it, add only if missing (grep -q || echo >>), or use Ansible lineinfile/blockinfile.

Q. Extract a time window from a 20 GB log fast.

sed -n '/^10:00/,/^10:05/{p;/^10:05/q}' stops at the end; or awk with time compare; LC_ALL=C helps.

Q. Safely insert a value that may contain / and &.

Escape it first: esc=$(printf '%s' "$V" | sed 's/[&/\]/\\&/g'); then sed "s/x/$esc/". Or use a different tool (envsubst, templates).

Try at home

  1. Write 10 lines of a shopping list. Use sed to change 'kg' to 'KG', delete lines with 'chips', and print only lines 3 to 6.
  2. Copy /etc/hosts to your home folder and practise sed -i.bak on the copy, then compare with diff.

Practise this chapter

Interview questions and answers

How would you safely change a repeated token only on intended lines?

I would choose a narrow address or matching pattern, preview without editing and compare examples that should and should not change. I would decide whether all occurrences on one line need the global flag. Then I would use the backed-up scratch edit and compare it with the original.

Check your understanding

Choose an answer, then compare your reasoning with the explanation.

0 of 3 answered correctly
1. What does s/FOO/BAR/ output for FOO FOO on one line?

Answer and explanation

A. BAR FOO

Without g, this substitution changes the first match on each selected line.

2. What does adding g change?

Answer and explanation

C. It replaces all matching occurrences on the selected line

The global substitution flag affects matches within a line. In-place editing is separate.

3. How do you confirm an in-place test changed only desired lines?

Answer and explanation

A. Compare the result with the scratch backup

A diff against the backup provides specific evidence of the changed lines.

Practice Tasks

Practice checks run in your browser. They check the answer for this exercise; they do not create resources or connect to your AWS account.

About this scenario

Amravati Agro Market is a agriculture business in Amravati. Anjali Thakre looks after its IT and cloud work. They count money in INR and run their AWS resources in the ap-south-1 Region. In the tasks below you do real jobs for them using what this lesson teaches. All names, account IDs, IP addresses and numbers are made up for practice.

0 / 16

Easy Replace first match

Fix a typo in output.

Print notes.txt with the first 'colour' on each line replaced by 'color'. Use s/colour/color/ in quotes.

  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Easy Replace all matches

Every http must become https.

Print links.txt replacing every http: with https: on every line.

  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Easy Print one line

See only line 5.

Print only line 5 of data.txt with sed.

  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Easy Delete blank lines

Clean output.

Print list.txt without empty lines using sed and the pattern ^$.

  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Easy Drop the header

CSV header breaks sums.

Print leads.csv without its first line using sed.

  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Easy Global flag

Replace every match on a line.

Which single letter at the end of s/a/b/ replaces all matches on a line?

  1. Write down the numbers the task gives you.
  2. Work it out step by step on paper.
  3. Type only the final answer in the box.
  4. Click Check answer.

Medium Edit a file in place

Change the port in the real file.

Change every 8080 to 9090 directly inside app.conf.

  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Medium In place with a backup

Undo is easy with a .bak.

Replace every DEBUG with INFO inside log.conf, keeping a backup log.conf.bak.

  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Medium Print a line range

Read part of a big file.

Print lines 10 to 20 of app.log with sed.

  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Medium Delete comment lines

Show only active config.

Print my.cnf without lines starting with #.

  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Medium Stop after 3 lines

Fast on huge files.

Print the first 3 lines of big.log with sed and quit.

  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Medium Different delimiter for paths

Slashes in paths clash with s///.

Replace /var/www with /srv/www in site.conf, printing the result. Use | as the delimiter.

  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Hard Append a line after a match

Add a setting under its section.

In php.ini (in place), add the line max_execution_time = 60 after the line matching ^\[PHP\].

  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Hard Swap with groups

Turn "Last, First" into "First Last".

Using -E, print names.txt changing 'Patil, Asha' style lines to 'Asha Patil'. Pattern: s/([^,]+), (.+)/\2 \1/.

  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Hard Two edits in one run

One pass is faster and safer.

In one sed command with two -e options, print app.env with dev replaced by prod and then 8080 replaced by 80 (first match each).

  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Hard Write matches to a file

Split errors out.

Using sed -n, write lines of api.log that contain TIMEOUT into timeouts.txt.

  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

In short

  1. s/old/new/g replaces; any separator works.
  2. -i edits; -i.bak keeps a backup; dry-run first.
  3. Addresses: N, $, /re/, N,M, /a/,/b/, !.
  4. d p i a c q = w are the line commands.
  5. -E with ( ) and \1 for reordering.
  6. Make edits idempotent and validate configs.

Revision, comparison and interview cards

Revise this lesson in a few minutes. Save the cards on your phone or download them as PNG files. The QR code on each card opens this lesson.

sed find and replace. Edit text without opening files. s/old/new/g replaces all. -i edits in place; add .bak. Change a port safely.
Revision card: sed find and replace · Download PNG · Open card page
sed line commands. Pick, delete or add lines. Np print, d delete, a/i add. Use -n with p. Drop comments and blanks.
Revision card: sed line commands · Download PNG · Open card page
sed p vs sed d. Prints matching lines. / Deletes matching lines.
Comparison: sed p vs sed d · Download PNG · Open card page
sed vs sed -i. Prints to screen. / Changes the file.
Comparison: sed vs sed -i · Download PNG · Open card page
Is sed -i safe in prod?. It overwrites the file. Test without -i, keep .bak. Edit with backup.
Interview card: Is sed -i safe in prod? · Download PNG · Open card page
Replace paths with slashes?. / clashes with s///. Use another delimiter. Change a web root.
Interview card: Replace paths with slashes? · Download PNG · Open card page
sed -i fails on macOS?. BSD sed needs a suffix. Give an empty one. macOS form.
Interview card: sed -i fails on macOS? · Download PNG · Open card page
Make sed edits repeatable?. Runs twice may double edits. Match the full old value. Set a value exactly.
Interview card: Make sed edits repeatable? · Download PNG · Open card page

More cards: Ravi Sir's Cards.