0
0
Bash-scriptingHow-ToBeginner · 4 min read

How to Use sed in Bash: Basic Syntax and Examples

In bash, sed is a command-line tool used to find and replace text or perform other text transformations on input streams or files. You use it by specifying a script or command like sed 's/old/new/' filename to replace text in a file or input.
📐

Syntax

The basic syntax of sed is:

  • sed [options] 'script' inputfile
  • script is usually a command like s/old/new/ which means substitute old text with new text.
  • inputfile is the file to process. If omitted, sed reads from standard input.

Common options include -i to edit files in place and -e to add multiple commands.

bash
sed 's/old_text/new_text/' filename
💻

Example

This example replaces the word apple with orange in a file named fruits.txt and prints the result to the terminal.

bash
echo "I like apple pie." > fruits.txt
sed 's/apple/orange/' fruits.txt
Output
I like orange pie.
⚠️

Common Pitfalls

Common mistakes when using sed include:

  • Forgetting to use quotes around the script, which can cause shell errors.
  • Not using the -i option when you want to edit files directly.
  • Using the wrong delimiter in the substitute command, especially if the text contains slashes.

Example of wrong and right usage:

bash
sed s/apple/orange/ fruits.txt  # Wrong: no quotes, may cause errors
sed 's/apple/orange/' fruits.txt  # Right: quotes used
sed -i 's/apple/orange/' fruits.txt  # Right: edits file in place
📊

Quick Reference

CommandDescription
sed 's/old/new/' fileReplace first occurrence of 'old' with 'new' in each line
sed -i 's/old/new/' fileEdit file in place replacing 'old' with 'new'
sed -e 'cmd1' -e 'cmd2' fileRun multiple sed commands
sed '/pattern/d' fileDelete lines matching 'pattern'
sed '2,4d' fileDelete lines 2 to 4

Key Takeaways

Use single quotes around sed scripts to avoid shell interpretation issues.
The basic sed command for substitution is s/old/new/.
Use -i option to edit files directly instead of printing to terminal.
You can chain multiple sed commands with -e option.
Be careful with delimiters if your text contains slashes; you can use other characters like s|old|new|.