View selected lines of a document/file
# sed -n ‘9,20p’ file.txt
View the entire file except selected lines
# sed ‘21,40d’ file.txt
Replacing words or characters in a file
# sed ‘s/centos/ubuntu/g’ file.txt
To make changes permanent, you can use option ‘-i’
# sed -i ‘s/centos/ubuntu/g’ file.txt
flag /g (global replacement)
Use the combination of /1, /2 etc and /g to replace all the patterns from the nth occurrence of a pattern in the file.
# sed ‘s/centos/ubuntu/4g’ file.txt
Using regular expressions
To remove empty lines or those beginning with
# from the Apache configuration file, do:
# sed ‘/^#|^$| *#/d’ my.cnf
The caret sign followed by the number sign
(^#) indicates the beginning of a line, whereas
^$ represents blank lines. The vertical bars indicate boolean operations, whereas the backward slash is used to escape the vertical bars.
In this particular case, the Apache configuration file has lines with
#’s not at the beginning of some lines, so
*# is used to remove those as well.
To replace a word beginning with uppercase or lowercase with another word, we can also use sed. To illustrate, let’s replace the word zip or Zip with rar in file.txt:
# sed ‘s/[Zz]ip/tar.gz/g’ file.txt
Performing multiple substitutions in a single command
# sed -i ‘s/ubuntu/centos/gi;s/plesk/cpanel/gi’ file.txt
Combine sed with other commands
Firstly, replace multiple blank spaces with a single space, we will use the output of
ip route show and a pipeline
Print the lines beginning with src.
Then convert multiple spaces into a single one. Finally, cut the 9th field (considering a single space as field separator), which is where the IP address is:
# ip route show | sed -n ‘/src/p’ | sed -e ‘s/ */ /g’ | cut -d’ ‘ -f9