In this tutorial, you will learn how to use sed
, a stream editor, for modifying and substituting text in shell scripts. The sed
command is a powerful tool that manipulates and transforms text, making it an invaluable resource for scripting and programming.
Throughout this tutorial, we will:
- Understand the basic syntax of sed
- Learn how to perform a simple text substitution
- Explore more complex text manipulations
Prerequisites: Basic knowledge of Linux command line is beneficial.
sed
uses a simple syntax: sed 's/old/new/' filename
. This command replaces the first occurrence of the word "old" with "new" in each line of the file "filename".
Here are some useful tips:
- To replace all occurrences in a line, add g
at the end: sed 's/old/new/g' filename
- To replace on a specific line number, add the line number before s
: sed '5s/old/new/' filename
- To replace within a range of lines, specify the range before s
: sed '5,10s/old/new/' filename
Example 1: Simple text substitution
echo "Hello world" | sed 's/world/universe/'
This echo command outputs "Hello world", which is then piped into sed
. sed
replaces "world" with "universe". The output is "Hello universe".
Example 2: Replace all occurrences
echo "Hello world world" | sed 's/world/universe/g'
In this case, sed
replaces both occurrences of "world" with "universe", resulting in "Hello universe universe".
Example 3: Replace on a specific line number
sed '2s/foo/bar/' filename
This replaces the first occurrence of "foo" with "bar" on the second line of the file.
In this tutorial, we have covered:
- The basic syntax of sed
- How to substitute text with sed
- How to perform more complex text manipulations
As next steps, you may want to learn about more advanced sed
features such as pattern deletion and multi-line transformations. You can find more information in the sed
documentation here.
Exercise 1:
Replace "apple" with "banana" in the following string:
"apple is red"
Exercise 2:
Replace the third occurrence of "cat" with "dog" in the following string:
"cat cat cat cat cat"
Exercise 3:
Replace "foo" with "bar" only on lines 10 to 20 in a given file.
Solutions:
1. echo "apple is red" | sed 's/apple/banana/'
- This will output "banana is red".
2. echo "cat cat cat cat cat" | sed 's/cat/dog/3'
- This will output "cat cat dog cat cat".
3. sed '10,20s/foo/bar/' filename
- This will replace "foo" with "bar" only on lines 10 to 20 in the file.
Remember, practice is crucial for mastering sed
. Try to incorporate it in your scripts and see the magic it can perform. Good luck!