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' inputfilescriptis usually a command likes/old/new/which means substitute old text with new text.inputfileis the file to process. If omitted,sedreads 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/' filenameExample
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
-ioption 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
| Command | Description |
|---|---|
| sed 's/old/new/' file | Replace first occurrence of 'old' with 'new' in each line |
| sed -i 's/old/new/' file | Edit file in place replacing 'old' with 'new' |
| sed -e 'cmd1' -e 'cmd2' file | Run multiple sed commands |
| sed '/pattern/d' file | Delete lines matching 'pattern' |
| sed '2,4d' file | Delete 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|.