sed

What is sed?

sed is a multi purpose tool that can be used for many endpoints. The way sed will be used in this matter is by replacing different words and characters, and finally pushing them to another file, or a file itself.

How to use sed

Be sure to understand the pipe command first

# syntax
sed <QUERY> <FILE>

##### make a test file with the contents of /etc/passwd
cat /etc/passwd > test.txt

##### examples 1
sed 's/root/ROOT/g' test.txt # changes all the words in the file test.txt that match root to ROOT (only in the terminal, not in the file)
sed 's/root/ROOT/1' test.txt # changes the first match (root) in the file test.txt that matches root to ROOT (only in the terminal, not in the file)
sed 's/root/ROOT/2' test.txt # changes the second match (root) in the file test.txt that matches root to ROOT (only in the terminal, not in the file)

##### examples 2
cat test.txt | sed 's/root/ROOT/g' # changes all the words in the file test.txt that match root to ROOT (only in the terminal, not in the file)
cat test.txt | sed 's/root/ROOT/1' # changes the first match (root) in the file test.txt that matches root to ROOT (only in the terminal, not in the file)
cat test.txt | sed 's/root/ROOT/2' # changes the second match (root) in the file test.txt that matches root to ROOT (only in the terminal, not in the file)

##### make changes on a specific line
sed '3 s/usr/USR/g' test.txt # makes the change only on line 3 of the file

##### make changes on multiple specific lines
sed '2,4 s/usr/USR/g' test.txt # makes the change on line 2, 3 and 4.

##### Submit the changes to the file
sed -i 's/root/ROOT/g' test.txt # success
sed -i 's/root/ROOT/1' test.txt # success
sed -i 's/root/ROOT/2' test.txt # success

cat test.txt | sed -i 's/root/ROOT/g' # failure
cat test.txt | sed -i 's/root/ROOT/1' # failure
cat test.txt | sed -i 's/root/ROOT/2' # failure

sed --help # get help from the tool
sed --version # get the current version of the tool

Last updated