Introduction to Sed
sed
(stream editor) is a powerful tool for parsing and transforming text. It's often used to make automated edits to files or output streams. Let's start with some basic sed
operations.
First, create a new file to work with:
echo -e "Hello, world\nThis is a test\nHello, labex\nWorld of Linux" > sed_test.txt
This creates a file named sed_test.txt
in your current directory with four lines of text.
Now, let's use sed
to replace text:
sed 's/Hello/Hi/' sed_test.txt
This command replaces the first occurrence of "Hello" with "Hi" on each line. By default, sed
only replaces the first match in each line.
Note: In this example, since "Hello" appears only once per line, it seems like all instances are replaced even without the g
flag.
To better understand the effect of the g
flag, let's modify sed_test.txt
so that there are multiple occurrences of "Hello" on the same line:
echo -e "Hello, world. Hello everyone\nThis is a test\nHello, labex says Hello\nWorld of Linux" > sed_test.txt
Now, the content of sed_test.txt
is:
Hello, world. Hello everyone
This is a test
Hello, labex says Hello
World of Linux
Run the replacement command again without the g
flag:
sed 's/Hello/Hi/' sed_test.txt
The output will be:
Hi, world. Hello everyone
This is a test
Hi, labex says Hello
World of Linux
You can see that only the first "Hello" on each line is replaced.
Now, perform a global replacement using the g
flag:
sed 's/Hello/Hi/g' sed_test.txt
The output will be:
Hi, world. Hi everyone
This is a test
Hi, labex says Hi
World of Linux
This time, all occurrences of "Hello" on each line are replaced with "Hi".
Explanation:
sed 's/Hello/Hi/'
: Replaces the first matching "Hello" in each line.
sed 's/Hello/Hi/g'
: Replaces all matching "Hello" in each line.
- The
g
flag stands for "global", indicating that the substitution should be made for every occurrence in the line.
Note that these commands do not modify the file itself; they only print the modified text to the terminal. To edit the file in-place, use the -i
option:
sed -i 's/Hello/Hi/g' sed_test.txt
Now, check the contents of the file to see the changes:
cat sed_test.txt