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

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.

What you'll learn 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

Why do we need this?

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.

What is it?

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 to do it (step by step)

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, sed never changes the file. It only prints.

2. Find and replace with s///

Why do we need this?

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

What is it?

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

How to do it (step by step)

  1. Replace the first match per line.
echo 'Poona to Poona' | sed 's/Poona/Pune/'

Output:

Pune to Poona

What it means: Only the first one changed.

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

Output:

Pune to Pune

What it means: 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;

What it means: 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

What it means: 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

What it means: & 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

What it means: -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$

What it means: [[:space:]] also covers \r.

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

Why do we need this?

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

What is it?

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.

How to do it (step by step)

  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

What it means: 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

What it means: The original is safe in .bak.

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

Output:

(no output)

What it means: 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

What it means: Every .yml file is updated.

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

Output:

(no output)

What it means: Undo is one move.

4. Addresses: choose which lines

Why do we need this?

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

What is it?

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 #

How to do it (step by step)

  1. Print lines 20 to 25.
sed -n '20,25p' app.log

Output:

(6 lines)

What it means: -n plus p prints only the range.

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

Output:

10:59:59 INFO shutdown

What it means: $ 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

What it means: 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

What it means: 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

What it means: ! negates the address.

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

Output:

2
4
6

What it means: first~step (GNU sed).

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

Why do we need this?

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

What is it?

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

How to do it (step by step)

  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;

What it means: 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

What it means: 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

What it means: 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

What it means: a adds after the matched line.

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

Output:

SELINUX=permissive

What it means: c replaces the full line, whatever it was.

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

Output:

10

What it means: 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

What it means: w saves matches without a pipe.

6. Extended regex, groups and back-references

Why do we need this?

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

What is it?

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.

How to do it (step by step)

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

Output:

Ravindra Bagale

What it means: \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

What it means: 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

What it means: 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

What it means: \U ... \E (GNU sed).

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

Output:

3.2.0

What it means: Print only the captured version.

7. Many commands, scripts and safe habits

Why do we need this?

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

What is it?

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.

How to do it (step by step)

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

Output:

env=prod
port=8080

What it means: -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

What it means: { } 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

What it means: 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)

What it means: Runs safely many times.

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

Output:

57
90
131

What it means: = prints the line number of each match.

8. Real examples from many industries

Why do we need this?

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

What is it?

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

How to do it (step by step)

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

Why do we need this?

Everyone hits these errors. Knowing the cause saves hours.

What is it?

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

How to do it (step by step)

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

Why do we need this?

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

What is it?

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

How to do it (step by step)

  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

Why do we need this?

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

What is it?

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

How to do it (step by step)

  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

Why do we need this?

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

What is it?

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

How to do it (step by step)

  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.

Practice Tasks

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

Why: Fix a typo in output.

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

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

Why: Every http must become https.

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

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

Why: See only line 5.

What to do: Print only line 5 of data.txt with sed.

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

Why: Clean output.

What to do: Print list.txt without empty lines using sed and the pattern ^$.

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

Why: CSV header breaks sums.

What to do: Print leads.csv without its first line using sed.

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

Why: Replace every match on a line.

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

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

Why: Change the port in the real file.

What to do: Change every 8080 to 9090 directly inside app.conf.

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

Why: Undo is easy with a .bak.

What to do: Replace every DEBUG with INFO inside log.conf, keeping a backup log.conf.bak.

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

Why: Read part of a big file.

What to do: Print lines 10 to 20 of app.log with sed.

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

Why: Show only active config.

What to do: Print my.cnf without lines starting with #.

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

Why: Fast on huge files.

What to do: Print the first 3 lines of big.log with sed and quit.

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

Why: Slashes in paths clash with s///.

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

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

Why: Add a setting under its section.

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

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

Why: Turn "Last, First" into "First Last".

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

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

Why: One pass is faster and safer.

What to do: 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).

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

Why: Split errors out.

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

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