Sed - perform basic transformations on an input stream i.e. a file or a stream input from a pipeline.
Example: replace all occurrences of TCP to UDP in network.log file
$ sed 's/TCP/UDP/' network.log > modified-network.log
Common sed command line options
-i : edit in place i.e. sed -i 's/TCP/UDP/' network.log
-n <line number>p e.g. print on line no 30 from network.log sed -n '30p' network.log
-e : expression e.g. sed -e 's/TCP/UDP/' network.log
[ here 's' stand for substitute ]
Basic regular expression overview
. : (dot) matches any single character
* : matches a sequence of zero or more instances e.g.
$ echo 'hostname=localhost.myorg.com' | sed 's/l.
l/myappserver/' *
^ : indicates the beginning of the line
$ : indicates the end of the line
[list] or
[^list] :matches any single char in a list. e.g. [1-9] matches any digit from 1 to 9
\+ : As *, matches any single or multiple instances of chars
\?: As *, matches any zero or one instances of chars
\{i\}: matches exactly
i sequences 'i is between 0 to 255'
\{i,\} : matches more than or equal to
i sequences
regex1|regex2 : matches regular expression 1 or regular expression 2
[a-z0-9A-z]: matches any ASCII chars
=====================================
Examples
-------------------
# find and replace any os name with Ubuntu
e.g.
1.
input: osname: centOS7
output: osname: Ubantu
2.
input: winOS: Windows-10
output: osname: Ubantu
3.
input: MacOS:Mac10
output: osname: Ubantu
Solution:
key=
echo "<input string>" | cut -d ":" -f 1
echo "<input string" | sed -e 's/^$key:\s
.$/$key: Ubantu/g'
first store the key i.e. left side label
^ - start of line
\s* - zero or more space charaters
.* - any zero or multiple charaters
$ - end of the line
-------------------------------------
Extract the line containing IP address from a file
sed -rn '/([0-9]{1,3}\.){3}[0-9]{1,3}/p' /etc/hosts